1 //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains code dealing with the IR generation for cleanups
11 // and related information.
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.
18 //===----------------------------------------------------------------------===//
20 #include "CGCleanup.h"
21 #include "CodeGenFunction.h"
22 #include "llvm/Support/SaveAndRestore.h"
24 using namespace clang;
25 using namespace CodeGen;
27 bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
29 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
31 return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
35 DominatingValue<RValue>::saved_type
36 DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
38 llvm::Value *V = rv.getScalarVal();
40 // These automatically dominate and don't need to be saved.
41 if (!DominatingLLVMValue::needsSaving(V))
42 return saved_type(V, ScalarLiteral);
44 // Everything else needs an alloca.
46 CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
47 CGF.Builder.CreateStore(V, addr);
48 return saved_type(addr.getPointer(), ScalarAddress);
52 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
53 llvm::Type *ComplexTy =
54 llvm::StructType::get(V.first->getType(), V.second->getType());
55 Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
56 CGF.Builder.CreateStore(V.first,
57 CGF.Builder.CreateStructGEP(addr, 0, CharUnits()));
58 CharUnits offset = CharUnits::fromQuantity(
59 CGF.CGM.getDataLayout().getTypeAllocSize(V.first->getType()));
60 CGF.Builder.CreateStore(V.second,
61 CGF.Builder.CreateStructGEP(addr, 1, offset));
62 return saved_type(addr.getPointer(), ComplexAddress);
65 assert(rv.isAggregate());
66 Address V = rv.getAggregateAddress(); // TODO: volatile?
67 if (!DominatingLLVMValue::needsSaving(V.getPointer()))
68 return saved_type(V.getPointer(), AggregateLiteral,
69 V.getAlignment().getQuantity());
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());
78 /// Given a saved r-value produced by SaveRValue, perform the code
79 /// necessary to restore it to usability at the current insertion
81 RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
82 auto getSavingAddress = [&](llvm::Value *value) {
83 auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
84 return Address(value, CharUnits::fromQuantity(alignment));
88 return RValue::get(Value);
90 return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
91 case AggregateLiteral:
92 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)));
97 case ComplexAddress: {
98 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));
105 return RValue::getComplex(real, imag);
109 llvm_unreachable("bad saved r-value kind");
112 /// Push an entry of the given size onto this protected-scope stack.
113 char *EHScopeStack::allocate(size_t Size) {
114 Size = llvm::alignTo(Size, ScopeStackAlignment);
115 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);
124 unsigned NewCapacity = CurrentCapacity;
127 } while (NewCapacity < UsedCapacity + Size);
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;
139 assert(StartOfBuffer + Size <= StartOfData);
144 void EHScopeStack::deallocate(size_t Size) {
145 StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
148 bool 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())
159 bool 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();
173 EHScopeStack::stable_iterator
174 EHScopeStack::getInnermostActiveNormalCleanup() const {
175 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
177 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
178 if (cleanup.isActive()) return si;
179 si = cleanup.getEnclosingNormalCleanup();
185 void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
186 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
187 bool IsNormalCleanup = Kind & NormalCleanup;
188 bool IsEHCleanup = Kind & EHCleanup;
189 bool IsActive = !(Kind & InactiveCleanup);
190 bool IsLifetimeMarker = Kind & LifetimeMarker;
191 EHCleanupScope *Scope =
192 new (Buffer) EHCleanupScope(IsNormalCleanup,
197 InnermostNormalCleanup,
200 InnermostNormalCleanup = stable_begin();
202 InnermostEHScope = stable_begin();
203 if (IsLifetimeMarker)
204 Scope->setLifetimeMarker();
206 return Scope->getCleanupBuffer();
209 void EHScopeStack::popCleanup() {
210 assert(!empty() && "popping exception stack when not empty");
212 assert(isa<EHCleanupScope>(*begin()));
213 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
214 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
215 InnermostEHScope = Cleanup.getEnclosingEHScope();
216 deallocate(Cleanup.getAllocatedSize());
218 // Destroy the cleanup.
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
225 if (!hasNormalCleanups())
226 BranchFixups.clear();
228 // Otherwise we can still trim out unnecessary nulls.
234 EHFilterScope *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();
242 void EHScopeStack::popFilter() {
243 assert(!empty() && "popping exception stack when not empty");
245 EHFilterScope &filter = cast<EHFilterScope>(*begin());
246 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
248 InnermostEHScope = filter.getEnclosingEHScope();
251 EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
252 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
253 EHCatchScope *scope =
254 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
255 InnermostEHScope = stable_begin();
259 void EHScopeStack::pushTerminate() {
260 char *Buffer = allocate(EHTerminateScope::getSize());
261 new (Buffer) EHTerminateScope(InnermostEHScope);
262 InnermostEHScope = stable_begin();
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.
270 void 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());
275 EHScopeStack::iterator it = find(InnermostNormalCleanup);
276 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
277 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
279 while (BranchFixups.size() > MinSize &&
280 BranchFixups.back().Destination == nullptr)
281 BranchFixups.pop_back();
284 Address CodeGenFunction::createCleanupActiveFlag() {
285 // Create a variable to decide whether the cleanup needs to be run.
286 Address active = CreateTempAllocaWithoutCast(
287 Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
289 // Initialize it to false at a site that's guaranteed to be run
290 // before each evaluation.
291 setBeforeOutermostConditional(Builder.getFalse(), active);
293 // Initialize it to true at the current location.
294 Builder.CreateStore(Builder.getTrue(), active);
299 void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
300 // Set that as the active flag in the cleanup.
301 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
302 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
303 cleanup.setActiveFlag(ActiveFlag);
305 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
306 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
309 void EHScopeStack::Cleanup::anchor() {}
311 static void createStoreInstBefore(llvm::Value *value, Address addr,
312 llvm::Instruction *beforeInst) {
313 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
314 store->setAlignment(addr.getAlignment().getQuantity());
317 static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
318 llvm::Instruction *beforeInst) {
319 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
320 load->setAlignment(addr.getAlignment().getQuantity());
324 /// All the branch fixups on the EH stack have propagated out past the
325 /// outermost normal cleanup; resolve them all by adding cases to the
326 /// given switch instruction.
327 static void ResolveAllBranchFixups(CodeGenFunction &CGF,
328 llvm::SwitchInst *Switch,
329 llvm::BasicBlock *CleanupEntry) {
330 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
332 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
333 // Skip this fixup if its destination isn't set.
334 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
335 if (Fixup.Destination == nullptr) continue;
337 // If there isn't an OptimisticBranchBlock, then InitialBranch is
338 // still pointing directly to its destination; forward it to the
339 // appropriate cleanup entry. This is required in the specific
341 // { std::string s; goto lbl; }
343 // i.e. where there's an unresolved fixup inside a single cleanup
344 // entry which we're currently popping.
345 if (Fixup.OptimisticBranchBlock == nullptr) {
346 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
347 CGF.getNormalCleanupDestSlot(),
348 Fixup.InitialBranch);
349 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
352 // Don't add this case to the switch statement twice.
353 if (!CasesAdded.insert(Fixup.Destination).second)
356 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
360 CGF.EHStack.clearFixups();
363 /// Transitions the terminator of the given exit-block of a cleanup to
364 /// be a cleanup switch.
365 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
366 llvm::BasicBlock *Block) {
367 // If it's a branch, turn it into a switch whose default
368 // destination is its original target.
369 llvm::TerminatorInst *Term = Block->getTerminator();
370 assert(Term && "can't transition block without terminator");
372 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
373 assert(Br->isUnconditional());
374 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
375 "cleanup.dest", Term);
376 llvm::SwitchInst *Switch =
377 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
378 Br->eraseFromParent();
381 return cast<llvm::SwitchInst>(Term);
385 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
386 assert(Block && "resolving a null target block");
387 if (!EHStack.getNumBranchFixups()) return;
389 assert(EHStack.hasNormalCleanups() &&
390 "branch fixups exist with no normal cleanups on stack");
392 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
393 bool ResolvedAny = false;
395 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
396 // Skip this fixup if its destination doesn't match.
397 BranchFixup &Fixup = EHStack.getBranchFixup(I);
398 if (Fixup.Destination != Block) continue;
400 Fixup.Destination = nullptr;
403 // If it doesn't have an optimistic branch block, LatestBranch is
404 // already pointing to the right place.
405 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
409 // Don't process the same optimistic branch block twice.
410 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
413 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
415 // Add a case to the switch.
416 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
420 EHStack.popNullFixups();
423 /// Pops cleanup blocks until the given savepoint is reached.
424 void CodeGenFunction::PopCleanupBlocks(
425 EHScopeStack::stable_iterator Old,
426 std::initializer_list<llvm::Value **> ValuesToReload) {
427 assert(Old.isValid());
429 bool HadBranches = false;
430 while (EHStack.stable_begin() != Old) {
431 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
432 HadBranches |= Scope.hasBranches();
434 // As long as Old strictly encloses the scope's enclosing normal
435 // cleanup, we're going to emit another normal cleanup which
436 // fallthrough can propagate through.
437 bool FallThroughIsBranchThrough =
438 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
440 PopCleanupBlock(FallThroughIsBranchThrough);
443 // If we didn't have any branches, the insertion point before cleanups must
444 // dominate the current insertion point and we don't need to reload any
449 // Spill and reload all values that the caller wants to be live at the current
451 for (llvm::Value **ReloadedValue : ValuesToReload) {
452 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
456 // Don't spill static allocas, they dominate all cleanups. These are created
457 // by binding a reference to a local variable or temporary.
458 auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
459 if (AI && AI->isStaticAlloca())
463 CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
465 // Find an insertion point after Inst and spill it to the temporary.
466 llvm::BasicBlock::iterator InsertBefore;
467 if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
468 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
470 InsertBefore = std::next(Inst->getIterator());
471 CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
473 // Reload the value at the current insertion point.
474 *ReloadedValue = Builder.CreateLoad(Tmp);
478 /// Pops cleanup blocks until the given savepoint is reached, then add the
479 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
480 void CodeGenFunction::PopCleanupBlocks(
481 EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
482 std::initializer_list<llvm::Value **> ValuesToReload) {
483 PopCleanupBlocks(Old, ValuesToReload);
485 // Move our deferred cleanups onto the EH stack.
486 for (size_t I = OldLifetimeExtendedSize,
487 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
488 // Alignment should be guaranteed by the vptrs in the individual cleanups.
489 assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
490 "misaligned cleanup stack entry");
492 LifetimeExtendedCleanupHeader &Header =
493 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
494 LifetimeExtendedCleanupStack[I]);
497 EHStack.pushCopyOfCleanup(Header.getKind(),
498 &LifetimeExtendedCleanupStack[I],
500 I += Header.getSize();
502 if (Header.isConditional()) {
504 reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
505 initFullExprCleanupWithFlag(ActiveFlag);
506 I += sizeof(ActiveFlag);
509 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
512 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
513 EHCleanupScope &Scope) {
514 assert(Scope.isNormalCleanup());
515 llvm::BasicBlock *Entry = Scope.getNormalBlock();
517 Entry = CGF.createBasicBlock("cleanup");
518 Scope.setNormalBlock(Entry);
523 /// Attempts to reduce a cleanup's entry block to a fallthrough. This
524 /// is basically llvm::MergeBlockIntoPredecessor, except
525 /// simplified/optimized for the tighter constraints on cleanup blocks.
527 /// Returns the new block, whatever it is.
528 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
529 llvm::BasicBlock *Entry) {
530 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
531 if (!Pred) return Entry;
533 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
534 if (!Br || Br->isConditional()) return Entry;
535 assert(Br->getSuccessor(0) == Entry);
537 // If we were previously inserting at the end of the cleanup entry
538 // block, we'll need to continue inserting at the end of the
540 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
541 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
544 Br->eraseFromParent();
546 // Replace all uses of the entry with the predecessor, in case there
547 // are phis in the cleanup.
548 Entry->replaceAllUsesWith(Pred);
551 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
553 // Kill the entry block.
554 Entry->eraseFromParent();
557 CGF.Builder.SetInsertPoint(Pred);
562 static void EmitCleanup(CodeGenFunction &CGF,
563 EHScopeStack::Cleanup *Fn,
564 EHScopeStack::Cleanup::Flags flags,
565 Address ActiveFlag) {
566 // If there's an active flag, load it and skip the cleanup if it's
568 llvm::BasicBlock *ContBB = nullptr;
569 if (ActiveFlag.isValid()) {
570 ContBB = CGF.createBasicBlock("cleanup.done");
571 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
572 llvm::Value *IsActive
573 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
574 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
575 CGF.EmitBlock(CleanupBB);
578 // Ask the cleanup to emit itself.
579 Fn->Emit(CGF, flags);
580 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
582 // Emit the continuation block if there was an active flag.
583 if (ActiveFlag.isValid())
584 CGF.EmitBlock(ContBB);
587 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
588 llvm::BasicBlock *From,
589 llvm::BasicBlock *To) {
590 // Exit is the exit block of a cleanup, so it always terminates in
591 // an unconditional branch or a switch.
592 llvm::TerminatorInst *Term = Exit->getTerminator();
594 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
595 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
596 Br->setSuccessor(0, To);
598 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
599 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
600 if (Switch->getSuccessor(I) == From)
601 Switch->setSuccessor(I, To);
605 /// We don't need a normal entry block for the given cleanup.
606 /// Optimistic fixup branches can cause these blocks to come into
607 /// existence anyway; if so, destroy it.
609 /// The validity of this transformation is very much specific to the
610 /// exact ways in which we form branches to cleanup entries.
611 static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
612 EHCleanupScope &scope) {
613 llvm::BasicBlock *entry = scope.getNormalBlock();
616 // Replace all the uses with unreachable.
617 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
618 for (llvm::BasicBlock::use_iterator
619 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
623 use.set(unreachableBB);
625 // The only uses should be fixup switches.
626 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
627 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
628 // Replace the switch with a branch.
629 llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
631 // The switch operand is a load from the cleanup-dest alloca.
632 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
634 // Destroy the switch.
635 si->eraseFromParent();
638 assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
639 assert(condition->use_empty());
640 condition->eraseFromParent();
644 assert(entry->use_empty());
648 /// Pops a cleanup block. If the block includes a normal cleanup, the
649 /// current insertion point is threaded through the cleanup, as are
650 /// any branch fixups on the cleanup.
651 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
652 assert(!EHStack.empty() && "cleanup stack is empty!");
653 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
654 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
655 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
657 // Remember activation information.
658 bool IsActive = Scope.isActive();
659 Address NormalActiveFlag =
660 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
661 : Address::invalid();
662 Address EHActiveFlag =
663 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
664 : Address::invalid();
666 // Check whether we need an EH cleanup. This is only true if we've
667 // generated a lazy EH cleanup block.
668 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
669 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
670 bool RequiresEHCleanup = (EHEntry != nullptr);
671 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
673 // Check the three conditions which might require a normal cleanup:
675 // - whether there are branch fix-ups through this cleanup
676 unsigned FixupDepth = Scope.getFixupDepth();
677 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
679 // - whether there are branch-throughs or branch-afters
680 bool HasExistingBranches = Scope.hasBranches();
682 // - whether there's a fallthrough
683 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
684 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
686 // Branch-through fall-throughs leave the insertion point set to the
687 // end of the last cleanup, which points to the current scope. The
688 // rest of IR gen doesn't need to worry about this; it only happens
689 // during the execution of PopCleanupBlocks().
690 bool HasPrebranchedFallthrough =
691 (FallthroughSource && FallthroughSource->getTerminator());
693 // If this is a normal cleanup, then having a prebranched
694 // fallthrough implies that the fallthrough source unconditionally
696 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
697 (Scope.getNormalBlock() &&
698 FallthroughSource->getTerminator()->getSuccessor(0)
699 == Scope.getNormalBlock()));
701 bool RequiresNormalCleanup = false;
702 if (Scope.isNormalCleanup() &&
703 (HasFixups || HasExistingBranches || HasFallthrough)) {
704 RequiresNormalCleanup = true;
707 // If we have a prebranched fallthrough into an inactive normal
708 // cleanup, rewrite it so that it leads to the appropriate place.
709 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
710 llvm::BasicBlock *prebranchDest;
712 // If the prebranch is semantically branching through the next
713 // cleanup, just forward it to the next block, leaving the
714 // insertion point in the prebranched block.
715 if (FallthroughIsBranchThrough) {
716 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
717 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
719 // Otherwise, we need to make a new block. If the normal cleanup
720 // isn't being used at all, we could actually reuse the normal
721 // entry block, but this is simpler, and it avoids conflicts with
722 // dead optimistic fixup branches.
724 prebranchDest = createBasicBlock("forwarded-prebranch");
725 EmitBlock(prebranchDest);
728 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
729 assert(normalEntry && !normalEntry->use_empty());
731 ForwardPrebranchedFallthrough(FallthroughSource,
732 normalEntry, prebranchDest);
735 // If we don't need the cleanup at all, we're done.
736 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
737 destroyOptimisticNormalEntry(*this, Scope);
738 EHStack.popCleanup(); // safe because there are no fixups
739 assert(EHStack.getNumBranchFixups() == 0 ||
740 EHStack.hasNormalCleanups());
744 // Copy the cleanup emission data out. This uses either a stack
745 // array or malloc'd memory, depending on the size, which is
746 // behavior that SmallVector would provide, if we could use it
747 // here. Unfortunately, if you ask for a SmallVector<char>, the
748 // alignment isn't sufficient.
749 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
750 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
751 std::unique_ptr<char[]> CleanupBufferHeap;
752 size_t CleanupSize = Scope.getCleanupSize();
753 EHScopeStack::Cleanup *Fn;
755 if (CleanupSize <= sizeof(CleanupBufferStack)) {
756 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
757 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
759 CleanupBufferHeap.reset(new char[CleanupSize]);
760 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
761 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
764 EHScopeStack::Cleanup::Flags cleanupFlags;
765 if (Scope.isNormalCleanup())
766 cleanupFlags.setIsNormalCleanupKind();
767 if (Scope.isEHCleanup())
768 cleanupFlags.setIsEHCleanupKind();
770 if (!RequiresNormalCleanup) {
771 destroyOptimisticNormalEntry(*this, Scope);
772 EHStack.popCleanup();
774 // If we have a fallthrough and no other need for the cleanup,
776 if (HasFallthrough && !HasPrebranchedFallthrough &&
777 !HasFixups && !HasExistingBranches) {
779 destroyOptimisticNormalEntry(*this, Scope);
780 EHStack.popCleanup();
782 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
784 // Otherwise, the best approach is to thread everything through
785 // the cleanup block and then try to clean up after ourselves.
787 // Force the entry block to exist.
788 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
790 // I. Set up the fallthrough edge in.
792 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
794 // If there's a fallthrough, we need to store the cleanup
795 // destination index. For fall-throughs this is always zero.
796 if (HasFallthrough) {
797 if (!HasPrebranchedFallthrough)
798 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
800 // Otherwise, save and clear the IP if we don't have fallthrough
801 // because the cleanup is inactive.
802 } else if (FallthroughSource) {
803 assert(!IsActive && "source without fallthrough for active cleanup");
804 savedInactiveFallthroughIP = Builder.saveAndClearIP();
807 // II. Emit the entry block. This implicitly branches to it if
808 // we have fallthrough. All the fixups and existing branches
809 // should already be branched to it.
810 EmitBlock(NormalEntry);
812 // III. Figure out where we're going and build the cleanup
815 bool HasEnclosingCleanups =
816 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
818 // Compute the branch-through dest if we need it:
819 // - if there are branch-throughs threaded through the scope
820 // - if fall-through is a branch-through
821 // - if there are fixups that will be optimistically forwarded
822 // to the enclosing cleanup
823 llvm::BasicBlock *BranchThroughDest = nullptr;
824 if (Scope.hasBranchThroughs() ||
825 (FallthroughSource && FallthroughIsBranchThrough) ||
826 (HasFixups && HasEnclosingCleanups)) {
827 assert(HasEnclosingCleanups);
828 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
829 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
832 llvm::BasicBlock *FallthroughDest = nullptr;
833 SmallVector<llvm::Instruction*, 2> InstsToAppend;
835 // If there's exactly one branch-after and no other threads,
836 // we can route it without a switch.
837 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
838 Scope.getNumBranchAfters() == 1) {
839 assert(!BranchThroughDest || !IsActive);
841 // Clean up the possibly dead store to the cleanup dest slot.
842 llvm::Instruction *NormalCleanupDestSlot =
843 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
844 if (NormalCleanupDestSlot->hasOneUse()) {
845 NormalCleanupDestSlot->user_back()->eraseFromParent();
846 NormalCleanupDestSlot->eraseFromParent();
847 NormalCleanupDest = Address::invalid();
850 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
851 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
853 // Build a switch-out if we need it:
854 // - if there are branch-afters threaded through the scope
855 // - if fall-through is a branch-after
856 // - if there are fixups that have nowhere left to go and
857 // so must be immediately resolved
858 } else if (Scope.getNumBranchAfters() ||
859 (HasFallthrough && !FallthroughIsBranchThrough) ||
860 (HasFixups && !HasEnclosingCleanups)) {
862 llvm::BasicBlock *Default =
863 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
865 // TODO: base this on the number of branch-afters and fixups
866 const unsigned SwitchCapacity = 10;
868 llvm::LoadInst *Load =
869 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
871 llvm::SwitchInst *Switch =
872 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
874 InstsToAppend.push_back(Load);
875 InstsToAppend.push_back(Switch);
877 // Branch-after fallthrough.
878 if (FallthroughSource && !FallthroughIsBranchThrough) {
879 FallthroughDest = createBasicBlock("cleanup.cont");
881 Switch->addCase(Builder.getInt32(0), FallthroughDest);
884 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
885 Switch->addCase(Scope.getBranchAfterIndex(I),
886 Scope.getBranchAfterBlock(I));
889 // If there aren't any enclosing cleanups, we can resolve all
891 if (HasFixups && !HasEnclosingCleanups)
892 ResolveAllBranchFixups(*this, Switch, NormalEntry);
894 // We should always have a branch-through destination in this case.
895 assert(BranchThroughDest);
896 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
899 // IV. Pop the cleanup and emit it.
900 EHStack.popCleanup();
901 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
903 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
905 // Append the prepared cleanup prologue from above.
906 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
907 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
908 NormalExit->getInstList().push_back(InstsToAppend[I]);
910 // Optimistically hope that any fixups will continue falling through.
911 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
913 BranchFixup &Fixup = EHStack.getBranchFixup(I);
914 if (!Fixup.Destination) continue;
915 if (!Fixup.OptimisticBranchBlock) {
916 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
917 getNormalCleanupDestSlot(),
918 Fixup.InitialBranch);
919 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
921 Fixup.OptimisticBranchBlock = NormalExit;
924 // V. Set up the fallthrough edge out.
926 // Case 1: a fallthrough source exists but doesn't branch to the
927 // cleanup because the cleanup is inactive.
928 if (!HasFallthrough && FallthroughSource) {
929 // Prebranched fallthrough was forwarded earlier.
930 // Non-prebranched fallthrough doesn't need to be forwarded.
931 // Either way, all we need to do is restore the IP we cleared before.
933 Builder.restoreIP(savedInactiveFallthroughIP);
935 // Case 2: a fallthrough source exists and should branch to the
936 // cleanup, but we're not supposed to branch through to the next
938 } else if (HasFallthrough && FallthroughDest) {
939 assert(!FallthroughIsBranchThrough);
940 EmitBlock(FallthroughDest);
942 // Case 3: a fallthrough source exists and should branch to the
943 // cleanup and then through to the next.
944 } else if (HasFallthrough) {
945 // Everything is already set up for this.
947 // Case 4: no fallthrough source exists.
949 Builder.ClearInsertionPoint();
952 // VI. Assorted cleaning.
954 // Check whether we can merge NormalEntry into a single predecessor.
955 // This might invalidate (non-IR) pointers to NormalEntry.
956 llvm::BasicBlock *NewNormalEntry =
957 SimplifyCleanupEntry(*this, NormalEntry);
959 // If it did invalidate those pointers, and NormalEntry was the same
960 // as NormalExit, go back and patch up the fixups.
961 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
962 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
964 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
968 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
970 // Emit the EH cleanup if required.
971 if (RequiresEHCleanup) {
972 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
976 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
978 // Push a terminate scope or cleanupendpad scope around the potentially
979 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
980 // program termination when cleanups throw.
981 bool PushedTerminate = false;
982 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
984 llvm::CleanupPadInst *CPI = nullptr;
986 const EHPersonality &Personality = EHPersonality::get(*this);
987 if (Personality.usesFuncletPads()) {
988 llvm::Value *ParentPad = CurrentFuncletPad;
990 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
991 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
994 // Non-MSVC personalities need to terminate when an EH cleanup throws.
995 if (!Personality.isMSVCPersonality()) {
996 EHStack.pushTerminate();
997 PushedTerminate = true;
1000 // We only actually emit the cleanup code if the cleanup is either
1001 // active or was used before it was deactivated.
1002 if (EHActiveFlag.isValid() || IsActive) {
1003 cleanupFlags.setIsForEHCleanup();
1004 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1008 Builder.CreateCleanupRet(CPI, NextAction);
1010 Builder.CreateBr(NextAction);
1012 // Leave the terminate scope.
1013 if (PushedTerminate)
1014 EHStack.popTerminate();
1016 Builder.restoreIP(SavedIP);
1018 SimplifyCleanupEntry(*this, EHEntry);
1022 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1023 /// specified destination obviously has no cleanups to run. 'false' is always
1024 /// a conservatively correct answer for this method.
1025 bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1026 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1027 && "stale jump destination");
1029 // Calculate the innermost active normal cleanup.
1030 EHScopeStack::stable_iterator TopCleanup =
1031 EHStack.getInnermostActiveNormalCleanup();
1033 // If we're not in an active normal cleanup scope, or if the
1034 // destination scope is within the innermost active normal cleanup
1035 // scope, we don't need to worry about fixups.
1036 if (TopCleanup == EHStack.stable_end() ||
1037 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1040 // Otherwise, we might need some cleanups.
1045 /// Terminate the current block by emitting a branch which might leave
1046 /// the current cleanup-protected scope. The target scope may not yet
1047 /// be known, in which case this will require a fixup.
1049 /// As a side-effect, this method clears the insertion point.
1050 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
1051 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1052 && "stale jump destination");
1054 if (!HaveInsertPoint())
1057 // Create the branch.
1058 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1060 // Calculate the innermost active normal cleanup.
1061 EHScopeStack::stable_iterator
1062 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1064 // If we're not in an active normal cleanup scope, or if the
1065 // destination scope is within the innermost active normal cleanup
1066 // scope, we don't need to worry about fixups.
1067 if (TopCleanup == EHStack.stable_end() ||
1068 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1069 Builder.ClearInsertionPoint();
1073 // If we can't resolve the destination cleanup scope, just add this
1074 // to the current cleanup scope as a branch fixup.
1075 if (!Dest.getScopeDepth().isValid()) {
1076 BranchFixup &Fixup = EHStack.addBranchFixup();
1077 Fixup.Destination = Dest.getBlock();
1078 Fixup.DestinationIndex = Dest.getDestIndex();
1079 Fixup.InitialBranch = BI;
1080 Fixup.OptimisticBranchBlock = nullptr;
1082 Builder.ClearInsertionPoint();
1086 // Otherwise, thread through all the normal cleanups in scope.
1088 // Store the index at the start.
1089 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1090 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
1092 // Adjust BI to point to the first cleanup block.
1094 EHCleanupScope &Scope =
1095 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1096 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1099 // Add this destination to all the scopes involved.
1100 EHScopeStack::stable_iterator I = TopCleanup;
1101 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1102 if (E.strictlyEncloses(I)) {
1104 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1105 assert(Scope.isNormalCleanup());
1106 I = Scope.getEnclosingNormalCleanup();
1108 // If this is the last cleanup we're propagating through, tell it
1109 // that there's a resolved jump moving through it.
1110 if (!E.strictlyEncloses(I)) {
1111 Scope.addBranchAfter(Index, Dest.getBlock());
1115 // Otherwise, tell the scope that there's a jump propagating
1116 // through it. If this isn't new information, all the rest of
1117 // the work has been done before.
1118 if (!Scope.addBranchThrough(Dest.getBlock()))
1123 Builder.ClearInsertionPoint();
1126 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1127 EHScopeStack::stable_iterator C) {
1128 // If we needed a normal block for any reason, that counts.
1129 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1132 // Check whether any enclosed cleanups were needed.
1133 for (EHScopeStack::stable_iterator
1134 I = EHStack.getInnermostNormalCleanup();
1136 assert(C.strictlyEncloses(I));
1137 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1138 if (S.getNormalBlock()) return true;
1139 I = S.getEnclosingNormalCleanup();
1145 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1146 EHScopeStack::stable_iterator cleanup) {
1147 // If we needed an EH block for any reason, that counts.
1148 if (EHStack.find(cleanup)->hasEHBranches())
1151 // Check whether any enclosed cleanups were needed.
1152 for (EHScopeStack::stable_iterator
1153 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1154 assert(cleanup.strictlyEncloses(i));
1156 EHScope &scope = *EHStack.find(i);
1157 if (scope.hasEHBranches())
1160 i = scope.getEnclosingEHScope();
1166 enum ForActivation_t {
1171 /// The given cleanup block is changing activation state. Configure a
1172 /// cleanup variable if necessary.
1174 /// It would be good if we had some way of determining if there were
1175 /// extra uses *after* the change-over point.
1176 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1177 EHScopeStack::stable_iterator C,
1178 ForActivation_t kind,
1179 llvm::Instruction *dominatingIP) {
1180 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1182 // We always need the flag if we're activating the cleanup in a
1183 // conditional context, because we have to assume that the current
1184 // location doesn't necessarily dominate the cleanup's code.
1185 bool isActivatedInConditional =
1186 (kind == ForActivation && CGF.isInConditionalBranch());
1188 bool needFlag = false;
1190 // Calculate whether the cleanup was used:
1192 // - as a normal cleanup
1193 if (Scope.isNormalCleanup() &&
1194 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1195 Scope.setTestFlagInNormalCleanup();
1199 // - as an EH cleanup
1200 if (Scope.isEHCleanup() &&
1201 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1202 Scope.setTestFlagInEHCleanup();
1206 // If it hasn't yet been used as either, we're done.
1207 if (!needFlag) return;
1209 Address var = Scope.getActiveFlag();
1210 if (!var.isValid()) {
1211 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1212 "cleanup.isactive");
1213 Scope.setActiveFlag(var);
1215 assert(dominatingIP && "no existing variable and no dominating IP!");
1217 // Initialize to true or false depending on whether it was
1218 // active up to this point.
1219 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1221 // If we're in a conditional block, ignore the dominating IP and
1222 // use the outermost conditional branch.
1223 if (CGF.isInConditionalBranch()) {
1224 CGF.setBeforeOutermostConditional(value, var);
1226 createStoreInstBefore(value, var, dominatingIP);
1230 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1233 /// Activate a cleanup that was created in an inactivated state.
1234 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1235 llvm::Instruction *dominatingIP) {
1236 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1237 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1238 assert(!Scope.isActive() && "double activation");
1240 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1242 Scope.setActive(true);
1245 /// Deactive a cleanup that was created in an active state.
1246 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1247 llvm::Instruction *dominatingIP) {
1248 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1249 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1250 assert(Scope.isActive() && "double deactivation");
1252 // If it's the top of the stack, just pop it, but do so only if it belongs
1253 // to the current RunCleanupsScope.
1254 if (C == EHStack.stable_begin() &&
1255 CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1256 // If it's a normal cleanup, we need to pretend that the
1257 // fallthrough is unreachable.
1258 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1260 Builder.restoreIP(SavedIP);
1264 // Otherwise, follow the general case.
1265 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1267 Scope.setActive(false);
1270 Address CodeGenFunction::getNormalCleanupDestSlot() {
1271 if (!NormalCleanupDest.isValid())
1273 CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1274 return NormalCleanupDest;
1277 /// Emits all the code to cause the given temporary to be cleaned up.
1278 void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1281 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1282 /*useEHCleanup*/ true);