blob: e8bcf0a3ac56409a963dbf42f20528fd5af2cdec [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"
Reid Klecknera002bd52015-10-28 23:06:42 +000022#include "llvm/Support/SaveAndRestore.h"
John McCalled1ae862011-01-28 11:13:47 +000023
24using namespace clang;
25using namespace CodeGen;
26
27bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
28 if (rv.isScalar())
29 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
30 if (rv.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +000031 return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
John McCalled1ae862011-01-28 11:13:47 +000032 return true;
33}
34
35DominatingValue<RValue>::saved_type
36DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
37 if (rv.isScalar()) {
38 llvm::Value *V = rv.getScalarVal();
39
40 // These automatically dominate and don't need to be saved.
41 if (!DominatingLLVMValue::needsSaving(V))
42 return saved_type(V, ScalarLiteral);
43
44 // Everything else needs an alloca.
John McCall7f416cc2015-09-08 08:05:57 +000045 Address addr =
46 CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
John McCalled1ae862011-01-28 11:13:47 +000047 CGF.Builder.CreateStore(V, addr);
John McCall7f416cc2015-09-08 08:05:57 +000048 return saved_type(addr.getPointer(), ScalarAddress);
John McCalled1ae862011-01-28 11:13:47 +000049 }
50
51 if (rv.isComplex()) {
52 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::Type *ComplexTy =
Serge Guelton1d993272017-05-09 19:31:30 +000054 llvm::StructType::get(V.first->getType(), V.second->getType());
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) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000114 Size = llvm::alignTo(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) {
Rui Ueyama83aa9792016-01-14 21:00:27 +0000145 StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
James Y Knight53c76162015-07-17 18:21:37 +0000146}
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
Akira Hatanaka8af7bb22016-04-01 22:58:55 +0000159bool EHScopeStack::requiresLandingPad() const {
160 for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
161 // Skip lifetime markers.
162 if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
163 if (cleanup->isLifetimeMarker()) {
164 si = cleanup->getEnclosingEHScope();
165 continue;
166 }
167 return true;
168 }
169
170 return false;
171}
172
John McCalled1ae862011-01-28 11:13:47 +0000173EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +0000174EHScopeStack::getInnermostActiveNormalCleanup() const {
175 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
176 si != se; ) {
177 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
178 if (cleanup.isActive()) return si;
179 si = cleanup.getEnclosingNormalCleanup();
180 }
181 return stable_end();
182}
183
John McCalled1ae862011-01-28 11:13:47 +0000184
185void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
John McCalled1ae862011-01-28 11:13:47 +0000186 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
187 bool IsNormalCleanup = Kind & NormalCleanup;
188 bool IsEHCleanup = Kind & EHCleanup;
189 bool IsActive = !(Kind & InactiveCleanup);
Tim Shen421119f2016-07-01 21:08:47 +0000190 bool IsLifetimeMarker = Kind & LifetimeMarker;
John McCalled1ae862011-01-28 11:13:47 +0000191 EHCleanupScope *Scope =
192 new (Buffer) EHCleanupScope(IsNormalCleanup,
193 IsEHCleanup,
194 IsActive,
195 Size,
196 BranchFixups.size(),
197 InnermostNormalCleanup,
John McCall8e4c74b2011-08-11 02:22:43 +0000198 InnermostEHScope);
John McCalled1ae862011-01-28 11:13:47 +0000199 if (IsNormalCleanup)
200 InnermostNormalCleanup = stable_begin();
201 if (IsEHCleanup)
John McCall8e4c74b2011-08-11 02:22:43 +0000202 InnermostEHScope = stable_begin();
Tim Shen421119f2016-07-01 21:08:47 +0000203 if (IsLifetimeMarker)
204 Scope->setLifetimeMarker();
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
265/// Remove any 'null' fixups on the stack. However, we can't pop more
266/// fixups than the fixup depth on the innermost normal cleanup, or
267/// else fixups that we try to add to that cleanup will end up in the
268/// wrong place. We *could* try to shrink fixup depths, but that's
269/// actually a lot of work for little benefit.
270void EHScopeStack::popNullFixups() {
271 // We expect this to only be called when there's still an innermost
272 // normal cleanup; otherwise there really shouldn't be any fixups.
273 assert(hasNormalCleanups());
274
275 EHScopeStack::iterator it = find(InnermostNormalCleanup);
276 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
277 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
278
279 while (BranchFixups.size() > MinSize &&
Craig Topper8a13c412014-05-21 05:09:00 +0000280 BranchFixups.back().Destination == nullptr)
John McCalled1ae862011-01-28 11:13:47 +0000281 BranchFixups.pop_back();
282}
283
284void CodeGenFunction::initFullExprCleanup() {
285 // Create a variable to decide whether the cleanup needs to be run.
John McCall7f416cc2015-09-08 08:05:57 +0000286 Address active = CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
287 "cleanup.cond");
John McCalled1ae862011-01-28 11:13:47 +0000288
289 // Initialize it to false at a site that's guaranteed to be run
290 // before each evaluation.
John McCallf4beacd2011-11-10 10:43:54 +0000291 setBeforeOutermostConditional(Builder.getFalse(), active);
John McCalled1ae862011-01-28 11:13:47 +0000292
293 // Initialize it to true at the current location.
294 Builder.CreateStore(Builder.getTrue(), active);
295
296 // Set that as the active flag in the cleanup.
297 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
John McCall7f416cc2015-09-08 08:05:57 +0000298 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
John McCalled1ae862011-01-28 11:13:47 +0000299 cleanup.setActiveFlag(active);
300
301 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
302 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
303}
304
John McCall5fcf8da2011-07-12 00:15:30 +0000305void EHScopeStack::Cleanup::anchor() {}
John McCalled1ae862011-01-28 11:13:47 +0000306
John McCall7f416cc2015-09-08 08:05:57 +0000307static void createStoreInstBefore(llvm::Value *value, Address addr,
308 llvm::Instruction *beforeInst) {
309 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
310 store->setAlignment(addr.getAlignment().getQuantity());
311}
312
313static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
314 llvm::Instruction *beforeInst) {
315 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
316 load->setAlignment(addr.getAlignment().getQuantity());
317 return load;
318}
319
John McCalled1ae862011-01-28 11:13:47 +0000320/// All the branch fixups on the EH stack have propagated out past the
321/// outermost normal cleanup; resolve them all by adding cases to the
322/// given switch instruction.
323static void ResolveAllBranchFixups(CodeGenFunction &CGF,
324 llvm::SwitchInst *Switch,
325 llvm::BasicBlock *CleanupEntry) {
326 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
327
328 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
329 // Skip this fixup if its destination isn't set.
330 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
Craig Topper8a13c412014-05-21 05:09:00 +0000331 if (Fixup.Destination == nullptr) continue;
John McCalled1ae862011-01-28 11:13:47 +0000332
333 // If there isn't an OptimisticBranchBlock, then InitialBranch is
334 // still pointing directly to its destination; forward it to the
335 // appropriate cleanup entry. This is required in the specific
336 // case of
337 // { std::string s; goto lbl; }
338 // lbl:
339 // i.e. where there's an unresolved fixup inside a single cleanup
340 // entry which we're currently popping.
Craig Topper8a13c412014-05-21 05:09:00 +0000341 if (Fixup.OptimisticBranchBlock == nullptr) {
John McCall7f416cc2015-09-08 08:05:57 +0000342 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
343 CGF.getNormalCleanupDestSlot(),
344 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000345 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
346 }
347
348 // Don't add this case to the switch statement twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000349 if (!CasesAdded.insert(Fixup.Destination).second)
350 continue;
John McCalled1ae862011-01-28 11:13:47 +0000351
352 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
353 Fixup.Destination);
354 }
355
356 CGF.EHStack.clearFixups();
357}
358
359/// Transitions the terminator of the given exit-block of a cleanup to
360/// be a cleanup switch.
361static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
362 llvm::BasicBlock *Block) {
363 // If it's a branch, turn it into a switch whose default
364 // destination is its original target.
365 llvm::TerminatorInst *Term = Block->getTerminator();
366 assert(Term && "can't transition block without terminator");
367
368 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
369 assert(Br->isUnconditional());
John McCall7f416cc2015-09-08 08:05:57 +0000370 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
371 "cleanup.dest", Term);
John McCalled1ae862011-01-28 11:13:47 +0000372 llvm::SwitchInst *Switch =
373 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
374 Br->eraseFromParent();
375 return Switch;
376 } else {
377 return cast<llvm::SwitchInst>(Term);
378 }
379}
380
381void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
382 assert(Block && "resolving a null target block");
383 if (!EHStack.getNumBranchFixups()) return;
384
385 assert(EHStack.hasNormalCleanups() &&
386 "branch fixups exist with no normal cleanups on stack");
387
388 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
389 bool ResolvedAny = false;
390
391 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
392 // Skip this fixup if its destination doesn't match.
393 BranchFixup &Fixup = EHStack.getBranchFixup(I);
394 if (Fixup.Destination != Block) continue;
395
Craig Topper8a13c412014-05-21 05:09:00 +0000396 Fixup.Destination = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000397 ResolvedAny = true;
398
399 // If it doesn't have an optimistic branch block, LatestBranch is
400 // already pointing to the right place.
401 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
402 if (!BranchBB)
403 continue;
404
405 // Don't process the same optimistic branch block twice.
David Blaikie82e95a32014-11-19 07:49:47 +0000406 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
John McCalled1ae862011-01-28 11:13:47 +0000407 continue;
408
409 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
410
411 // Add a case to the switch.
412 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
413 }
414
415 if (ResolvedAny)
416 EHStack.popNullFixups();
417}
418
419/// Pops cleanup blocks until the given savepoint is reached.
Reid Kleckner092d0652017-03-06 22:18:34 +0000420void CodeGenFunction::PopCleanupBlocks(
421 EHScopeStack::stable_iterator Old,
422 std::initializer_list<llvm::Value **> ValuesToReload) {
John McCalled1ae862011-01-28 11:13:47 +0000423 assert(Old.isValid());
424
Reid Kleckner092d0652017-03-06 22:18:34 +0000425 bool HadBranches = false;
John McCalled1ae862011-01-28 11:13:47 +0000426 while (EHStack.stable_begin() != Old) {
427 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
Reid Kleckner092d0652017-03-06 22:18:34 +0000428 HadBranches |= Scope.hasBranches();
John McCalled1ae862011-01-28 11:13:47 +0000429
430 // As long as Old strictly encloses the scope's enclosing normal
431 // cleanup, we're going to emit another normal cleanup which
432 // fallthrough can propagate through.
433 bool FallThroughIsBranchThrough =
434 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
435
Adrian Prantldc237b52013-05-16 00:41:26 +0000436 PopCleanupBlock(FallThroughIsBranchThrough);
John McCalled1ae862011-01-28 11:13:47 +0000437 }
Reid Kleckner092d0652017-03-06 22:18:34 +0000438
439 // If we didn't have any branches, the insertion point before cleanups must
440 // dominate the current insertion point and we don't need to reload any
441 // values.
442 if (!HadBranches)
443 return;
444
445 // Spill and reload all values that the caller wants to be live at the current
446 // insertion point.
447 for (llvm::Value **ReloadedValue : ValuesToReload) {
448 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
449 if (!Inst)
450 continue;
451 Address Tmp =
452 CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
453
454 // Find an insertion point after Inst and spill it to the temporary.
455 llvm::BasicBlock::iterator InsertBefore;
456 if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
457 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
458 else
459 InsertBefore = std::next(Inst->getIterator());
460 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
461
462 // Reload the value at the current insertion point.
463 *ReloadedValue = Builder.CreateLoad(Tmp);
464 }
John McCalled1ae862011-01-28 11:13:47 +0000465}
466
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000467/// Pops cleanup blocks until the given savepoint is reached, then add the
468/// cleanups from the given savepoint in the lifetime-extended cleanups stack.
Reid Kleckner092d0652017-03-06 22:18:34 +0000469void CodeGenFunction::PopCleanupBlocks(
470 EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
471 std::initializer_list<llvm::Value **> ValuesToReload) {
472 PopCleanupBlocks(Old, ValuesToReload);
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000473
474 // Move our deferred cleanups onto the EH stack.
Richard Smith736a9472013-06-12 20:42:33 +0000475 for (size_t I = OldLifetimeExtendedSize,
476 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
477 // Alignment should be guaranteed by the vptrs in the individual cleanups.
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000478 assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
Richard Smith736a9472013-06-12 20:42:33 +0000479 "misaligned cleanup stack entry");
480
481 LifetimeExtendedCleanupHeader &Header =
482 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
483 LifetimeExtendedCleanupStack[I]);
484 I += sizeof(Header);
485
486 EHStack.pushCopyOfCleanup(Header.getKind(),
487 &LifetimeExtendedCleanupStack[I],
488 Header.getSize());
489 I += Header.getSize();
490 }
491 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
492}
493
John McCalled1ae862011-01-28 11:13:47 +0000494static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
495 EHCleanupScope &Scope) {
496 assert(Scope.isNormalCleanup());
497 llvm::BasicBlock *Entry = Scope.getNormalBlock();
498 if (!Entry) {
499 Entry = CGF.createBasicBlock("cleanup");
500 Scope.setNormalBlock(Entry);
501 }
502 return Entry;
503}
504
John McCalled1ae862011-01-28 11:13:47 +0000505/// Attempts to reduce a cleanup's entry block to a fallthrough. This
506/// is basically llvm::MergeBlockIntoPredecessor, except
507/// simplified/optimized for the tighter constraints on cleanup blocks.
508///
509/// Returns the new block, whatever it is.
510static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
511 llvm::BasicBlock *Entry) {
512 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
513 if (!Pred) return Entry;
514
515 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
516 if (!Br || Br->isConditional()) return Entry;
517 assert(Br->getSuccessor(0) == Entry);
518
519 // If we were previously inserting at the end of the cleanup entry
520 // block, we'll need to continue inserting at the end of the
521 // predecessor.
522 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
523 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
524
525 // Kill the branch.
526 Br->eraseFromParent();
527
John McCalled1ae862011-01-28 11:13:47 +0000528 // Replace all uses of the entry with the predecessor, in case there
529 // are phis in the cleanup.
530 Entry->replaceAllUsesWith(Pred);
531
Jay Foade03c05c2011-06-20 14:38:01 +0000532 // Merge the blocks.
533 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
534
John McCalled1ae862011-01-28 11:13:47 +0000535 // Kill the entry block.
536 Entry->eraseFromParent();
537
538 if (WasInsertBlock)
539 CGF.Builder.SetInsertPoint(Pred);
540
541 return Pred;
542}
543
544static void EmitCleanup(CodeGenFunction &CGF,
545 EHScopeStack::Cleanup *Fn,
John McCall30317fd2011-07-12 20:27:29 +0000546 EHScopeStack::Cleanup::Flags flags,
John McCall7f416cc2015-09-08 08:05:57 +0000547 Address ActiveFlag) {
John McCalled1ae862011-01-28 11:13:47 +0000548 // If there's an active flag, load it and skip the cleanup if it's
549 // false.
Craig Topper8a13c412014-05-21 05:09:00 +0000550 llvm::BasicBlock *ContBB = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +0000551 if (ActiveFlag.isValid()) {
John McCalled1ae862011-01-28 11:13:47 +0000552 ContBB = CGF.createBasicBlock("cleanup.done");
553 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
554 llvm::Value *IsActive
555 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
556 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
557 CGF.EmitBlock(CleanupBB);
558 }
559
560 // Ask the cleanup to emit itself.
John McCall30317fd2011-07-12 20:27:29 +0000561 Fn->Emit(CGF, flags);
John McCalled1ae862011-01-28 11:13:47 +0000562 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
563
564 // Emit the continuation block if there was an active flag.
John McCall7f416cc2015-09-08 08:05:57 +0000565 if (ActiveFlag.isValid())
John McCalled1ae862011-01-28 11:13:47 +0000566 CGF.EmitBlock(ContBB);
John McCalled1ae862011-01-28 11:13:47 +0000567}
568
569static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
570 llvm::BasicBlock *From,
571 llvm::BasicBlock *To) {
572 // Exit is the exit block of a cleanup, so it always terminates in
573 // an unconditional branch or a switch.
574 llvm::TerminatorInst *Term = Exit->getTerminator();
575
576 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
577 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
578 Br->setSuccessor(0, To);
579 } else {
580 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
581 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
582 if (Switch->getSuccessor(I) == From)
583 Switch->setSuccessor(I, To);
584 }
585}
586
John McCallf82bdf62011-08-06 06:53:52 +0000587/// We don't need a normal entry block for the given cleanup.
588/// Optimistic fixup branches can cause these blocks to come into
589/// existence anyway; if so, destroy it.
590///
591/// The validity of this transformation is very much specific to the
592/// exact ways in which we form branches to cleanup entries.
593static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
594 EHCleanupScope &scope) {
595 llvm::BasicBlock *entry = scope.getNormalBlock();
596 if (!entry) return;
597
598 // Replace all the uses with unreachable.
599 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
600 for (llvm::BasicBlock::use_iterator
601 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
Chandler Carruth4d01fff2014-03-09 03:16:50 +0000602 llvm::Use &use = *i;
John McCallf82bdf62011-08-06 06:53:52 +0000603 ++i;
604
605 use.set(unreachableBB);
606
607 // The only uses should be fixup switches.
608 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
Stepan Dyatkovskiy5fecf5442012-02-01 07:50:21 +0000609 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
John McCallf82bdf62011-08-06 06:53:52 +0000610 // Replace the switch with a branch.
Chandler Carruth260161b2017-04-12 08:12:30 +0000611 llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
John McCallf82bdf62011-08-06 06:53:52 +0000612
613 // The switch operand is a load from the cleanup-dest alloca.
614 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
615
616 // Destroy the switch.
617 si->eraseFromParent();
618
619 // Destroy the load.
620 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
621 assert(condition->use_empty());
622 condition->eraseFromParent();
623 }
624 }
625
626 assert(entry->use_empty());
627 delete entry;
628}
629
John McCalled1ae862011-01-28 11:13:47 +0000630/// Pops a cleanup block. If the block includes a normal cleanup, the
631/// current insertion point is threaded through the cleanup, as are
632/// any branch fixups on the cleanup.
Adrian Prantldc237b52013-05-16 00:41:26 +0000633void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
John McCalled1ae862011-01-28 11:13:47 +0000634 assert(!EHStack.empty() && "cleanup stack is empty!");
635 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
636 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
637 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
638
639 // Remember activation information.
640 bool IsActive = Scope.isActive();
John McCall7f416cc2015-09-08 08:05:57 +0000641 Address NormalActiveFlag =
642 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
643 : Address::invalid();
644 Address EHActiveFlag =
645 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
646 : Address::invalid();
John McCalled1ae862011-01-28 11:13:47 +0000647
648 // Check whether we need an EH cleanup. This is only true if we've
649 // generated a lazy EH cleanup block.
John McCall8e4c74b2011-08-11 02:22:43 +0000650 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000651 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
652 bool RequiresEHCleanup = (EHEntry != nullptr);
John McCall8e4c74b2011-08-11 02:22:43 +0000653 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +0000654
655 // Check the three conditions which might require a normal cleanup:
656
657 // - whether there are branch fix-ups through this cleanup
658 unsigned FixupDepth = Scope.getFixupDepth();
659 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
660
661 // - whether there are branch-throughs or branch-afters
662 bool HasExistingBranches = Scope.hasBranches();
663
664 // - whether there's a fallthrough
665 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
Craig Topper8a13c412014-05-21 05:09:00 +0000666 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
John McCalled1ae862011-01-28 11:13:47 +0000667
668 // Branch-through fall-throughs leave the insertion point set to the
669 // end of the last cleanup, which points to the current scope. The
670 // rest of IR gen doesn't need to worry about this; it only happens
671 // during the execution of PopCleanupBlocks().
672 bool HasPrebranchedFallthrough =
673 (FallthroughSource && FallthroughSource->getTerminator());
674
675 // If this is a normal cleanup, then having a prebranched
676 // fallthrough implies that the fallthrough source unconditionally
677 // jumps here.
678 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
679 (Scope.getNormalBlock() &&
680 FallthroughSource->getTerminator()->getSuccessor(0)
681 == Scope.getNormalBlock()));
682
683 bool RequiresNormalCleanup = false;
684 if (Scope.isNormalCleanup() &&
685 (HasFixups || HasExistingBranches || HasFallthrough)) {
686 RequiresNormalCleanup = true;
687 }
688
John McCall45e42952011-08-07 07:05:57 +0000689 // If we have a prebranched fallthrough into an inactive normal
690 // cleanup, rewrite it so that it leads to the appropriate place.
691 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
692 llvm::BasicBlock *prebranchDest;
693
694 // If the prebranch is semantically branching through the next
695 // cleanup, just forward it to the next block, leaving the
696 // insertion point in the prebranched block.
John McCalled1ae862011-01-28 11:13:47 +0000697 if (FallthroughIsBranchThrough) {
John McCall45e42952011-08-07 07:05:57 +0000698 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
699 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
John McCalled1ae862011-01-28 11:13:47 +0000700
John McCall45e42952011-08-07 07:05:57 +0000701 // Otherwise, we need to make a new block. If the normal cleanup
702 // isn't being used at all, we could actually reuse the normal
703 // entry block, but this is simpler, and it avoids conflicts with
704 // dead optimistic fixup branches.
John McCalled1ae862011-01-28 11:13:47 +0000705 } else {
John McCall45e42952011-08-07 07:05:57 +0000706 prebranchDest = createBasicBlock("forwarded-prebranch");
707 EmitBlock(prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000708 }
John McCall45e42952011-08-07 07:05:57 +0000709
710 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
711 assert(normalEntry && !normalEntry->use_empty());
712
713 ForwardPrebranchedFallthrough(FallthroughSource,
714 normalEntry, prebranchDest);
John McCalled1ae862011-01-28 11:13:47 +0000715 }
716
717 // If we don't need the cleanup at all, we're done.
718 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000719 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000720 EHStack.popCleanup(); // safe because there are no fixups
721 assert(EHStack.getNumBranchFixups() == 0 ||
722 EHStack.hasNormalCleanups());
723 return;
724 }
725
James Y Knight54a3b262015-12-30 03:58:33 +0000726 // Copy the cleanup emission data out. This uses either a stack
727 // array or malloc'd memory, depending on the size, which is
728 // behavior that SmallVector would provide, if we could use it
729 // here. Unfortunately, if you ask for a SmallVector<char>, the
730 // alignment isn't sufficient.
Benjamin Kramer6c3e4ec2015-08-04 12:34:30 +0000731 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
James Y Knight54a3b262015-12-30 03:58:33 +0000732 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
733 std::unique_ptr<char[]> CleanupBufferHeap;
734 size_t CleanupSize = Scope.getCleanupSize();
735 EHScopeStack::Cleanup *Fn;
736
737 if (CleanupSize <= sizeof(CleanupBufferStack)) {
738 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
739 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
740 } else {
741 CleanupBufferHeap.reset(new char[CleanupSize]);
742 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
743 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
744 }
John McCalled1ae862011-01-28 11:13:47 +0000745
John McCall8e4c74b2011-08-11 02:22:43 +0000746 EHScopeStack::Cleanup::Flags cleanupFlags;
747 if (Scope.isNormalCleanup())
748 cleanupFlags.setIsNormalCleanupKind();
749 if (Scope.isEHCleanup())
750 cleanupFlags.setIsEHCleanupKind();
John McCalled1ae862011-01-28 11:13:47 +0000751
752 if (!RequiresNormalCleanup) {
John McCallf82bdf62011-08-06 06:53:52 +0000753 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000754 EHStack.popCleanup();
755 } else {
756 // If we have a fallthrough and no other need for the cleanup,
757 // emit it directly.
758 if (HasFallthrough && !HasPrebranchedFallthrough &&
759 !HasFixups && !HasExistingBranches) {
760
John McCallf82bdf62011-08-06 06:53:52 +0000761 destroyOptimisticNormalEntry(*this, Scope);
John McCalled1ae862011-01-28 11:13:47 +0000762 EHStack.popCleanup();
763
John McCall30317fd2011-07-12 20:27:29 +0000764 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000765
766 // Otherwise, the best approach is to thread everything through
767 // the cleanup block and then try to clean up after ourselves.
768 } else {
769 // Force the entry block to exist.
770 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
771
772 // I. Set up the fallthrough edge in.
773
John McCalla3654e32011-08-10 04:11:11 +0000774 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
John McCall45e42952011-08-07 07:05:57 +0000775
John McCalled1ae862011-01-28 11:13:47 +0000776 // If there's a fallthrough, we need to store the cleanup
777 // destination index. For fall-throughs this is always zero.
778 if (HasFallthrough) {
779 if (!HasPrebranchedFallthrough)
780 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
781
John McCall45e42952011-08-07 07:05:57 +0000782 // Otherwise, save and clear the IP if we don't have fallthrough
783 // because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000784 } else if (FallthroughSource) {
785 assert(!IsActive && "source without fallthrough for active cleanup");
John McCall45e42952011-08-07 07:05:57 +0000786 savedInactiveFallthroughIP = Builder.saveAndClearIP();
John McCalled1ae862011-01-28 11:13:47 +0000787 }
788
789 // II. Emit the entry block. This implicitly branches to it if
790 // we have fallthrough. All the fixups and existing branches
791 // should already be branched to it.
792 EmitBlock(NormalEntry);
793
794 // III. Figure out where we're going and build the cleanup
795 // epilogue.
796
797 bool HasEnclosingCleanups =
798 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
799
800 // Compute the branch-through dest if we need it:
801 // - if there are branch-throughs threaded through the scope
802 // - if fall-through is a branch-through
803 // - if there are fixups that will be optimistically forwarded
804 // to the enclosing cleanup
Craig Topper8a13c412014-05-21 05:09:00 +0000805 llvm::BasicBlock *BranchThroughDest = nullptr;
John McCalled1ae862011-01-28 11:13:47 +0000806 if (Scope.hasBranchThroughs() ||
807 (FallthroughSource && FallthroughIsBranchThrough) ||
808 (HasFixups && HasEnclosingCleanups)) {
809 assert(HasEnclosingCleanups);
810 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
811 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
812 }
813
Craig Topper8a13c412014-05-21 05:09:00 +0000814 llvm::BasicBlock *FallthroughDest = nullptr;
Benjamin Kramerc7497452015-02-17 16:53:08 +0000815 SmallVector<llvm::Instruction*, 2> InstsToAppend;
John McCalled1ae862011-01-28 11:13:47 +0000816
817 // If there's exactly one branch-after and no other threads,
818 // we can route it without a switch.
819 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
820 Scope.getNumBranchAfters() == 1) {
821 assert(!BranchThroughDest || !IsActive);
822
David Majnemerdc012fa2015-04-22 21:38:15 +0000823 // Clean up the possibly dead store to the cleanup dest slot.
824 llvm::Instruction *NormalCleanupDestSlot =
John McCall7f416cc2015-09-08 08:05:57 +0000825 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
David Majnemerdc012fa2015-04-22 21:38:15 +0000826 if (NormalCleanupDestSlot->hasOneUse()) {
827 NormalCleanupDestSlot->user_back()->eraseFromParent();
828 NormalCleanupDestSlot->eraseFromParent();
829 NormalCleanupDest = nullptr;
830 }
831
John McCalled1ae862011-01-28 11:13:47 +0000832 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
833 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
834
835 // Build a switch-out if we need it:
836 // - if there are branch-afters threaded through the scope
837 // - if fall-through is a branch-after
838 // - if there are fixups that have nowhere left to go and
839 // so must be immediately resolved
840 } else if (Scope.getNumBranchAfters() ||
841 (HasFallthrough && !FallthroughIsBranchThrough) ||
842 (HasFixups && !HasEnclosingCleanups)) {
843
844 llvm::BasicBlock *Default =
845 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
846
847 // TODO: base this on the number of branch-afters and fixups
848 const unsigned SwitchCapacity = 10;
849
850 llvm::LoadInst *Load =
John McCall7f416cc2015-09-08 08:05:57 +0000851 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
852 nullptr);
John McCalled1ae862011-01-28 11:13:47 +0000853 llvm::SwitchInst *Switch =
854 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
855
856 InstsToAppend.push_back(Load);
857 InstsToAppend.push_back(Switch);
858
859 // Branch-after fallthrough.
860 if (FallthroughSource && !FallthroughIsBranchThrough) {
861 FallthroughDest = createBasicBlock("cleanup.cont");
862 if (HasFallthrough)
863 Switch->addCase(Builder.getInt32(0), FallthroughDest);
864 }
865
866 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
867 Switch->addCase(Scope.getBranchAfterIndex(I),
868 Scope.getBranchAfterBlock(I));
869 }
870
871 // If there aren't any enclosing cleanups, we can resolve all
872 // the fixups now.
873 if (HasFixups && !HasEnclosingCleanups)
874 ResolveAllBranchFixups(*this, Switch, NormalEntry);
875 } else {
876 // We should always have a branch-through destination in this case.
877 assert(BranchThroughDest);
878 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
879 }
880
881 // IV. Pop the cleanup and emit it.
882 EHStack.popCleanup();
883 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
884
John McCall30317fd2011-07-12 20:27:29 +0000885 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
John McCalled1ae862011-01-28 11:13:47 +0000886
887 // Append the prepared cleanup prologue from above.
888 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
Benjamin Kramerc7497452015-02-17 16:53:08 +0000889 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
890 NormalExit->getInstList().push_back(InstsToAppend[I]);
John McCalled1ae862011-01-28 11:13:47 +0000891
892 // Optimistically hope that any fixups will continue falling through.
893 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
894 I < E; ++I) {
John McCallad7c5c12011-02-08 08:22:06 +0000895 BranchFixup &Fixup = EHStack.getBranchFixup(I);
John McCalled1ae862011-01-28 11:13:47 +0000896 if (!Fixup.Destination) continue;
897 if (!Fixup.OptimisticBranchBlock) {
John McCall7f416cc2015-09-08 08:05:57 +0000898 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
899 getNormalCleanupDestSlot(),
900 Fixup.InitialBranch);
John McCalled1ae862011-01-28 11:13:47 +0000901 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
902 }
903 Fixup.OptimisticBranchBlock = NormalExit;
904 }
905
906 // V. Set up the fallthrough edge out.
907
John McCall45e42952011-08-07 07:05:57 +0000908 // Case 1: a fallthrough source exists but doesn't branch to the
909 // cleanup because the cleanup is inactive.
John McCalled1ae862011-01-28 11:13:47 +0000910 if (!HasFallthrough && FallthroughSource) {
John McCall45e42952011-08-07 07:05:57 +0000911 // Prebranched fallthrough was forwarded earlier.
912 // Non-prebranched fallthrough doesn't need to be forwarded.
913 // Either way, all we need to do is restore the IP we cleared before.
John McCalled1ae862011-01-28 11:13:47 +0000914 assert(!IsActive);
John McCall45e42952011-08-07 07:05:57 +0000915 Builder.restoreIP(savedInactiveFallthroughIP);
John McCalled1ae862011-01-28 11:13:47 +0000916
917 // Case 2: a fallthrough source exists and should branch to the
918 // cleanup, but we're not supposed to branch through to the next
919 // cleanup.
920 } else if (HasFallthrough && FallthroughDest) {
921 assert(!FallthroughIsBranchThrough);
922 EmitBlock(FallthroughDest);
923
924 // Case 3: a fallthrough source exists and should branch to the
925 // cleanup and then through to the next.
926 } else if (HasFallthrough) {
927 // Everything is already set up for this.
928
929 // Case 4: no fallthrough source exists.
930 } else {
931 Builder.ClearInsertionPoint();
932 }
933
934 // VI. Assorted cleaning.
935
936 // Check whether we can merge NormalEntry into a single predecessor.
937 // This might invalidate (non-IR) pointers to NormalEntry.
938 llvm::BasicBlock *NewNormalEntry =
939 SimplifyCleanupEntry(*this, NormalEntry);
940
941 // If it did invalidate those pointers, and NormalEntry was the same
942 // as NormalExit, go back and patch up the fixups.
943 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
944 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
945 I < E; ++I)
John McCallad7c5c12011-02-08 08:22:06 +0000946 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
John McCalled1ae862011-01-28 11:13:47 +0000947 }
948 }
949
950 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
951
952 // Emit the EH cleanup if required.
953 if (RequiresEHCleanup) {
954 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
955
956 EmitBlock(EHEntry);
Reid Kleckner55391522015-10-08 21:14:56 +0000957
Reid Klecknera002bd52015-10-28 23:06:42 +0000958 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
959
960 // Push a terminate scope or cleanupendpad scope around the potentially
961 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
962 // program termination when cleanups throw.
Reid Kleckner55391522015-10-08 21:14:56 +0000963 bool PushedTerminate = false;
David Majnemer4e52d6f2015-12-12 05:39:21 +0000964 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
965 CurrentFuncletPad);
Reid Klecknera002bd52015-10-28 23:06:42 +0000966 llvm::CleanupPadInst *CPI = nullptr;
Reid Kleckner55391522015-10-08 21:14:56 +0000967 if (!EHPersonality::get(*this).usesFuncletPads()) {
968 EHStack.pushTerminate();
969 PushedTerminate = true;
Reid Klecknera002bd52015-10-28 23:06:42 +0000970 } else {
David Majnemer4e52d6f2015-12-12 05:39:21 +0000971 llvm::Value *ParentPad = CurrentFuncletPad;
972 if (!ParentPad)
973 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
974 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
Reid Kleckner55391522015-10-08 21:14:56 +0000975 }
976
Eli Friedmanabab7762012-08-02 00:10:24 +0000977 // We only actually emit the cleanup code if the cleanup is either
978 // active or was used before it was deactivated.
John McCall7f416cc2015-09-08 08:05:57 +0000979 if (EHActiveFlag.isValid() || IsActive) {
Eli Friedmanabab7762012-08-02 00:10:24 +0000980 cleanupFlags.setIsForEHCleanup();
981 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
982 }
John McCalled1ae862011-01-28 11:13:47 +0000983
David Majnemere888a2f2015-08-15 03:21:08 +0000984 if (CPI)
Joseph Tremouletce536a52015-08-23 00:26:48 +0000985 Builder.CreateCleanupRet(CPI, NextAction);
David Majnemerdbf10452015-07-31 17:58:45 +0000986 else
987 Builder.CreateBr(NextAction);
John McCalled1ae862011-01-28 11:13:47 +0000988
Reid Kleckner55391522015-10-08 21:14:56 +0000989 // Leave the terminate scope.
990 if (PushedTerminate)
991 EHStack.popTerminate();
992
John McCalled1ae862011-01-28 11:13:47 +0000993 Builder.restoreIP(SavedIP);
994
995 SimplifyCleanupEntry(*this, EHEntry);
996 }
997}
998
Justin Bognere25ffdf2014-01-21 00:35:11 +0000999/// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1000/// specified destination obviously has no cleanups to run. 'false' is always
1001/// a conservatively correct answer for this method.
1002bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1003 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1004 && "stale jump destination");
1005
1006 // Calculate the innermost active normal cleanup.
1007 EHScopeStack::stable_iterator TopCleanup =
1008 EHStack.getInnermostActiveNormalCleanup();
1009
1010 // If we're not in an active normal cleanup scope, or if the
1011 // destination scope is within the innermost active normal cleanup
1012 // scope, we don't need to worry about fixups.
1013 if (TopCleanup == EHStack.stable_end() ||
1014 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1015 return true;
1016
1017 // Otherwise, we might need some cleanups.
1018 return false;
1019}
1020
1021
John McCalled1ae862011-01-28 11:13:47 +00001022/// Terminate the current block by emitting a branch which might leave
1023/// the current cleanup-protected scope. The target scope may not yet
1024/// be known, in which case this will require a fixup.
1025///
1026/// As a side-effect, this method clears the insertion point.
1027void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
John McCall1b93f1b2011-02-25 04:19:13 +00001028 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
John McCalled1ae862011-01-28 11:13:47 +00001029 && "stale jump destination");
1030
1031 if (!HaveInsertPoint())
1032 return;
1033
1034 // Create the branch.
1035 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1036
1037 // Calculate the innermost active normal cleanup.
1038 EHScopeStack::stable_iterator
1039 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1040
1041 // If we're not in an active normal cleanup scope, or if the
1042 // destination scope is within the innermost active normal cleanup
1043 // scope, we don't need to worry about fixups.
1044 if (TopCleanup == EHStack.stable_end() ||
1045 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1046 Builder.ClearInsertionPoint();
1047 return;
1048 }
1049
1050 // If we can't resolve the destination cleanup scope, just add this
1051 // to the current cleanup scope as a branch fixup.
1052 if (!Dest.getScopeDepth().isValid()) {
1053 BranchFixup &Fixup = EHStack.addBranchFixup();
1054 Fixup.Destination = Dest.getBlock();
1055 Fixup.DestinationIndex = Dest.getDestIndex();
1056 Fixup.InitialBranch = BI;
Craig Topper8a13c412014-05-21 05:09:00 +00001057 Fixup.OptimisticBranchBlock = nullptr;
John McCalled1ae862011-01-28 11:13:47 +00001058
1059 Builder.ClearInsertionPoint();
1060 return;
1061 }
1062
1063 // Otherwise, thread through all the normal cleanups in scope.
1064
1065 // Store the index at the start.
1066 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
John McCall7f416cc2015-09-08 08:05:57 +00001067 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
John McCalled1ae862011-01-28 11:13:47 +00001068
1069 // Adjust BI to point to the first cleanup block.
1070 {
1071 EHCleanupScope &Scope =
1072 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1073 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1074 }
1075
1076 // Add this destination to all the scopes involved.
1077 EHScopeStack::stable_iterator I = TopCleanup;
1078 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1079 if (E.strictlyEncloses(I)) {
1080 while (true) {
1081 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1082 assert(Scope.isNormalCleanup());
1083 I = Scope.getEnclosingNormalCleanup();
1084
1085 // If this is the last cleanup we're propagating through, tell it
1086 // that there's a resolved jump moving through it.
1087 if (!E.strictlyEncloses(I)) {
1088 Scope.addBranchAfter(Index, Dest.getBlock());
1089 break;
1090 }
1091
1092 // Otherwise, tell the scope that there's a jump propoagating
1093 // through it. If this isn't new information, all the rest of
1094 // the work has been done before.
1095 if (!Scope.addBranchThrough(Dest.getBlock()))
1096 break;
1097 }
1098 }
1099
1100 Builder.ClearInsertionPoint();
1101}
1102
John McCalled1ae862011-01-28 11:13:47 +00001103static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1104 EHScopeStack::stable_iterator C) {
1105 // If we needed a normal block for any reason, that counts.
1106 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1107 return true;
1108
1109 // Check whether any enclosed cleanups were needed.
1110 for (EHScopeStack::stable_iterator
1111 I = EHStack.getInnermostNormalCleanup();
1112 I != C; ) {
1113 assert(C.strictlyEncloses(I));
1114 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1115 if (S.getNormalBlock()) return true;
1116 I = S.getEnclosingNormalCleanup();
1117 }
1118
1119 return false;
1120}
1121
1122static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
John McCall8e4c74b2011-08-11 02:22:43 +00001123 EHScopeStack::stable_iterator cleanup) {
John McCalled1ae862011-01-28 11:13:47 +00001124 // If we needed an EH block for any reason, that counts.
John McCall8e4c74b2011-08-11 02:22:43 +00001125 if (EHStack.find(cleanup)->hasEHBranches())
John McCalled1ae862011-01-28 11:13:47 +00001126 return true;
1127
1128 // Check whether any enclosed cleanups were needed.
1129 for (EHScopeStack::stable_iterator
John McCall8e4c74b2011-08-11 02:22:43 +00001130 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1131 assert(cleanup.strictlyEncloses(i));
1132
1133 EHScope &scope = *EHStack.find(i);
1134 if (scope.hasEHBranches())
1135 return true;
1136
1137 i = scope.getEnclosingEHScope();
John McCalled1ae862011-01-28 11:13:47 +00001138 }
1139
1140 return false;
1141}
1142
1143enum ForActivation_t {
1144 ForActivation,
1145 ForDeactivation
1146};
1147
1148/// The given cleanup block is changing activation state. Configure a
1149/// cleanup variable if necessary.
1150///
1151/// It would be good if we had some way of determining if there were
1152/// extra uses *after* the change-over point.
1153static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1154 EHScopeStack::stable_iterator C,
John McCallf4beacd2011-11-10 10:43:54 +00001155 ForActivation_t kind,
1156 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001157 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1158
John McCalle63abb52011-11-10 09:22:44 +00001159 // We always need the flag if we're activating the cleanup in a
1160 // conditional context, because we have to assume that the current
1161 // location doesn't necessarily dominate the cleanup's code.
1162 bool isActivatedInConditional =
John McCallf4beacd2011-11-10 10:43:54 +00001163 (kind == ForActivation && CGF.isInConditionalBranch());
John McCalle63abb52011-11-10 09:22:44 +00001164
1165 bool needFlag = false;
John McCalled1ae862011-01-28 11:13:47 +00001166
1167 // Calculate whether the cleanup was used:
1168
1169 // - as a normal cleanup
John McCalle63abb52011-11-10 09:22:44 +00001170 if (Scope.isNormalCleanup() &&
1171 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001172 Scope.setTestFlagInNormalCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001173 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001174 }
1175
1176 // - as an EH cleanup
John McCalle63abb52011-11-10 09:22:44 +00001177 if (Scope.isEHCleanup() &&
1178 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
John McCalled1ae862011-01-28 11:13:47 +00001179 Scope.setTestFlagInEHCleanup();
John McCalle63abb52011-11-10 09:22:44 +00001180 needFlag = true;
John McCalled1ae862011-01-28 11:13:47 +00001181 }
1182
1183 // If it hasn't yet been used as either, we're done.
John McCalle63abb52011-11-10 09:22:44 +00001184 if (!needFlag) return;
John McCalled1ae862011-01-28 11:13:47 +00001185
John McCall7f416cc2015-09-08 08:05:57 +00001186 Address var = Scope.getActiveFlag();
1187 if (!var.isValid()) {
1188 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1189 "cleanup.isactive");
John McCallf4beacd2011-11-10 10:43:54 +00001190 Scope.setActiveFlag(var);
1191
1192 assert(dominatingIP && "no existing variable and no dominating IP!");
John McCalled1ae862011-01-28 11:13:47 +00001193
1194 // Initialize to true or false depending on whether it was
1195 // active up to this point.
John McCall7f416cc2015-09-08 08:05:57 +00001196 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
John McCallf4beacd2011-11-10 10:43:54 +00001197
1198 // If we're in a conditional block, ignore the dominating IP and
1199 // use the outermost conditional branch.
1200 if (CGF.isInConditionalBranch()) {
1201 CGF.setBeforeOutermostConditional(value, var);
1202 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001203 createStoreInstBefore(value, var, dominatingIP);
John McCallf4beacd2011-11-10 10:43:54 +00001204 }
John McCalled1ae862011-01-28 11:13:47 +00001205 }
1206
John McCallf4beacd2011-11-10 10:43:54 +00001207 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
John McCalled1ae862011-01-28 11:13:47 +00001208}
1209
1210/// Activate a cleanup that was created in an inactivated state.
John McCallf4beacd2011-11-10 10:43:54 +00001211void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1212 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001213 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1214 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1215 assert(!Scope.isActive() && "double activation");
1216
John McCallf4beacd2011-11-10 10:43:54 +00001217 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001218
1219 Scope.setActive(true);
1220}
1221
1222/// Deactive a cleanup that was created in an active state.
John McCallf4beacd2011-11-10 10:43:54 +00001223void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1224 llvm::Instruction *dominatingIP) {
John McCalled1ae862011-01-28 11:13:47 +00001225 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1226 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1227 assert(Scope.isActive() && "double deactivation");
1228
1229 // If it's the top of the stack, just pop it.
1230 if (C == EHStack.stable_begin()) {
1231 // If it's a normal cleanup, we need to pretend that the
1232 // fallthrough is unreachable.
1233 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1234 PopCleanupBlock();
1235 Builder.restoreIP(SavedIP);
1236 return;
1237 }
1238
1239 // Otherwise, follow the general case.
John McCallf4beacd2011-11-10 10:43:54 +00001240 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
John McCalled1ae862011-01-28 11:13:47 +00001241
1242 Scope.setActive(false);
1243}
1244
John McCall7f416cc2015-09-08 08:05:57 +00001245Address CodeGenFunction::getNormalCleanupDestSlot() {
John McCalled1ae862011-01-28 11:13:47 +00001246 if (!NormalCleanupDest)
1247 NormalCleanupDest =
1248 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
John McCall7f416cc2015-09-08 08:05:57 +00001249 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
John McCalled1ae862011-01-28 11:13:47 +00001250}
Peter Collingbourne702b2842011-11-27 22:09:22 +00001251
1252/// Emits all the code to cause the given temporary to be cleaned up.
1253void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1254 QualType TempType,
John McCall7f416cc2015-09-08 08:05:57 +00001255 Address Ptr) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001256 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
Peter Collingbourne702b2842011-11-27 22:09:22 +00001257 /*useEHCleanup*/ true);
1258}