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(),
56 Address addr = CGF.CreateDefaultAlignTempAlloca(ComplexTy, "saved-complex");
57 CGF.Builder.CreateStore(V.first,
58 CGF.Builder.CreateStructGEP(addr, 0, CharUnits()));
59 CharUnits offset = CharUnits::fromQuantity(
60 CGF.CGM.getDataLayout().getTypeAllocSize(V.first->getType()));
61 CGF.Builder.CreateStore(V.second,
62 CGF.Builder.CreateStructGEP(addr, 1, offset));
63 return saved_type(addr.getPointer(), ComplexAddress);
66 assert(rv.isAggregate());
67 Address V = rv.getAggregateAddress(); // TODO: volatile?
68 if (!DominatingLLVMValue::needsSaving(V.getPointer()))
69 return saved_type(V.getPointer(), AggregateLiteral,
70 V.getAlignment().getQuantity());
73 CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
74 CGF.Builder.CreateStore(V.getPointer(), addr);
75 return saved_type(addr.getPointer(), AggregateAddress,
76 V.getAlignment().getQuantity());
79 /// Given a saved r-value produced by SaveRValue, perform the code
80 /// necessary to restore it to usability at the current insertion
82 RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
83 auto getSavingAddress = [&](llvm::Value *value) {
84 auto alignment = cast<llvm::AllocaInst>(value)->getAlignment();
85 return Address(value, CharUnits::fromQuantity(alignment));
89 return RValue::get(Value);
91 return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
92 case AggregateLiteral:
93 return RValue::getAggregate(Address(Value, CharUnits::fromQuantity(Align)));
94 case AggregateAddress: {
95 auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
96 return RValue::getAggregate(Address(addr, CharUnits::fromQuantity(Align)));
98 case ComplexAddress: {
99 Address address = getSavingAddress(Value);
100 llvm::Value *real = CGF.Builder.CreateLoad(
101 CGF.Builder.CreateStructGEP(address, 0, CharUnits()));
102 CharUnits offset = CharUnits::fromQuantity(
103 CGF.CGM.getDataLayout().getTypeAllocSize(real->getType()));
104 llvm::Value *imag = CGF.Builder.CreateLoad(
105 CGF.Builder.CreateStructGEP(address, 1, offset));
106 return RValue::getComplex(real, imag);
110 llvm_unreachable("bad saved r-value kind");
113 /// Push an entry of the given size onto this protected-scope stack.
114 char *EHScopeStack::allocate(size_t Size) {
115 Size = llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
116 if (!StartOfBuffer) {
117 unsigned Capacity = 1024;
118 while (Capacity < Size) Capacity *= 2;
119 StartOfBuffer = new char[Capacity];
120 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
121 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
122 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
123 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
125 unsigned NewCapacity = CurrentCapacity;
128 } while (NewCapacity < UsedCapacity + Size);
130 char *NewStartOfBuffer = new char[NewCapacity];
131 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
132 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
133 memcpy(NewStartOfData, StartOfData, UsedCapacity);
134 delete [] StartOfBuffer;
135 StartOfBuffer = NewStartOfBuffer;
136 EndOfBuffer = NewEndOfBuffer;
137 StartOfData = NewStartOfData;
140 assert(StartOfBuffer + Size <= StartOfData);
145 void EHScopeStack::deallocate(size_t Size) {
146 StartOfData += llvm::RoundUpToAlignment(Size, ScopeStackAlignment);
149 bool EHScopeStack::containsOnlyLifetimeMarkers(
150 EHScopeStack::stable_iterator Old) const {
151 for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
152 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
153 if (!cleanup || !cleanup->isLifetimeMarker())
160 EHScopeStack::stable_iterator
161 EHScopeStack::getInnermostActiveNormalCleanup() const {
162 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
164 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
165 if (cleanup.isActive()) return si;
166 si = cleanup.getEnclosingNormalCleanup();
172 void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
173 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
174 bool IsNormalCleanup = Kind & NormalCleanup;
175 bool IsEHCleanup = Kind & EHCleanup;
176 bool IsActive = !(Kind & InactiveCleanup);
177 EHCleanupScope *Scope =
178 new (Buffer) EHCleanupScope(IsNormalCleanup,
183 InnermostNormalCleanup,
186 InnermostNormalCleanup = stable_begin();
188 InnermostEHScope = stable_begin();
190 return Scope->getCleanupBuffer();
193 void EHScopeStack::popCleanup() {
194 assert(!empty() && "popping exception stack when not empty");
196 assert(isa<EHCleanupScope>(*begin()));
197 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
198 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
199 InnermostEHScope = Cleanup.getEnclosingEHScope();
200 deallocate(Cleanup.getAllocatedSize());
202 // Destroy the cleanup.
205 // Check whether we can shrink the branch-fixups stack.
206 if (!BranchFixups.empty()) {
207 // If we no longer have any normal cleanups, all the fixups are
209 if (!hasNormalCleanups())
210 BranchFixups.clear();
212 // Otherwise we can still trim out unnecessary nulls.
218 EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
219 assert(getInnermostEHScope() == stable_end());
220 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
221 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
222 InnermostEHScope = stable_begin();
226 void EHScopeStack::popFilter() {
227 assert(!empty() && "popping exception stack when not empty");
229 EHFilterScope &filter = cast<EHFilterScope>(*begin());
230 deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
232 InnermostEHScope = filter.getEnclosingEHScope();
235 EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
236 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
237 EHCatchScope *scope =
238 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
239 InnermostEHScope = stable_begin();
243 void EHScopeStack::pushTerminate() {
244 char *Buffer = allocate(EHTerminateScope::getSize());
245 new (Buffer) EHTerminateScope(InnermostEHScope);
246 InnermostEHScope = stable_begin();
249 /// Remove any 'null' fixups on the stack. However, we can't pop more
250 /// fixups than the fixup depth on the innermost normal cleanup, or
251 /// else fixups that we try to add to that cleanup will end up in the
252 /// wrong place. We *could* try to shrink fixup depths, but that's
253 /// actually a lot of work for little benefit.
254 void EHScopeStack::popNullFixups() {
255 // We expect this to only be called when there's still an innermost
256 // normal cleanup; otherwise there really shouldn't be any fixups.
257 assert(hasNormalCleanups());
259 EHScopeStack::iterator it = find(InnermostNormalCleanup);
260 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
261 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
263 while (BranchFixups.size() > MinSize &&
264 BranchFixups.back().Destination == nullptr)
265 BranchFixups.pop_back();
268 void CodeGenFunction::initFullExprCleanup() {
269 // Create a variable to decide whether the cleanup needs to be run.
270 Address active = CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
273 // Initialize it to false at a site that's guaranteed to be run
274 // before each evaluation.
275 setBeforeOutermostConditional(Builder.getFalse(), active);
277 // Initialize it to true at the current location.
278 Builder.CreateStore(Builder.getTrue(), active);
280 // Set that as the active flag in the cleanup.
281 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
282 assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
283 cleanup.setActiveFlag(active);
285 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
286 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
289 void EHScopeStack::Cleanup::anchor() {}
291 static void createStoreInstBefore(llvm::Value *value, Address addr,
292 llvm::Instruction *beforeInst) {
293 auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
294 store->setAlignment(addr.getAlignment().getQuantity());
297 static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
298 llvm::Instruction *beforeInst) {
299 auto load = new llvm::LoadInst(addr.getPointer(), name, beforeInst);
300 load->setAlignment(addr.getAlignment().getQuantity());
304 /// All the branch fixups on the EH stack have propagated out past the
305 /// outermost normal cleanup; resolve them all by adding cases to the
306 /// given switch instruction.
307 static void ResolveAllBranchFixups(CodeGenFunction &CGF,
308 llvm::SwitchInst *Switch,
309 llvm::BasicBlock *CleanupEntry) {
310 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
312 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
313 // Skip this fixup if its destination isn't set.
314 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
315 if (Fixup.Destination == nullptr) continue;
317 // If there isn't an OptimisticBranchBlock, then InitialBranch is
318 // still pointing directly to its destination; forward it to the
319 // appropriate cleanup entry. This is required in the specific
321 // { std::string s; goto lbl; }
323 // i.e. where there's an unresolved fixup inside a single cleanup
324 // entry which we're currently popping.
325 if (Fixup.OptimisticBranchBlock == nullptr) {
326 createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
327 CGF.getNormalCleanupDestSlot(),
328 Fixup.InitialBranch);
329 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
332 // Don't add this case to the switch statement twice.
333 if (!CasesAdded.insert(Fixup.Destination).second)
336 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
340 CGF.EHStack.clearFixups();
343 /// Transitions the terminator of the given exit-block of a cleanup to
344 /// be a cleanup switch.
345 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
346 llvm::BasicBlock *Block) {
347 // If it's a branch, turn it into a switch whose default
348 // destination is its original target.
349 llvm::TerminatorInst *Term = Block->getTerminator();
350 assert(Term && "can't transition block without terminator");
352 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
353 assert(Br->isUnconditional());
354 auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
355 "cleanup.dest", Term);
356 llvm::SwitchInst *Switch =
357 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
358 Br->eraseFromParent();
361 return cast<llvm::SwitchInst>(Term);
365 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
366 assert(Block && "resolving a null target block");
367 if (!EHStack.getNumBranchFixups()) return;
369 assert(EHStack.hasNormalCleanups() &&
370 "branch fixups exist with no normal cleanups on stack");
372 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
373 bool ResolvedAny = false;
375 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
376 // Skip this fixup if its destination doesn't match.
377 BranchFixup &Fixup = EHStack.getBranchFixup(I);
378 if (Fixup.Destination != Block) continue;
380 Fixup.Destination = nullptr;
383 // If it doesn't have an optimistic branch block, LatestBranch is
384 // already pointing to the right place.
385 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
389 // Don't process the same optimistic branch block twice.
390 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
393 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
395 // Add a case to the switch.
396 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
400 EHStack.popNullFixups();
403 /// Pops cleanup blocks until the given savepoint is reached.
404 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
405 assert(Old.isValid());
407 while (EHStack.stable_begin() != Old) {
408 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
410 // As long as Old strictly encloses the scope's enclosing normal
411 // cleanup, we're going to emit another normal cleanup which
412 // fallthrough can propagate through.
413 bool FallThroughIsBranchThrough =
414 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
416 PopCleanupBlock(FallThroughIsBranchThrough);
420 /// Pops cleanup blocks until the given savepoint is reached, then add the
421 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
423 CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
424 size_t OldLifetimeExtendedSize) {
425 PopCleanupBlocks(Old);
427 // Move our deferred cleanups onto the EH stack.
428 for (size_t I = OldLifetimeExtendedSize,
429 E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
430 // Alignment should be guaranteed by the vptrs in the individual cleanups.
431 assert((I % llvm::alignOf<LifetimeExtendedCleanupHeader>() == 0) &&
432 "misaligned cleanup stack entry");
434 LifetimeExtendedCleanupHeader &Header =
435 reinterpret_cast<LifetimeExtendedCleanupHeader&>(
436 LifetimeExtendedCleanupStack[I]);
439 EHStack.pushCopyOfCleanup(Header.getKind(),
440 &LifetimeExtendedCleanupStack[I],
442 I += Header.getSize();
444 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
447 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
448 EHCleanupScope &Scope) {
449 assert(Scope.isNormalCleanup());
450 llvm::BasicBlock *Entry = Scope.getNormalBlock();
452 Entry = CGF.createBasicBlock("cleanup");
453 Scope.setNormalBlock(Entry);
458 /// Attempts to reduce a cleanup's entry block to a fallthrough. This
459 /// is basically llvm::MergeBlockIntoPredecessor, except
460 /// simplified/optimized for the tighter constraints on cleanup blocks.
462 /// Returns the new block, whatever it is.
463 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
464 llvm::BasicBlock *Entry) {
465 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
466 if (!Pred) return Entry;
468 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
469 if (!Br || Br->isConditional()) return Entry;
470 assert(Br->getSuccessor(0) == Entry);
472 // If we were previously inserting at the end of the cleanup entry
473 // block, we'll need to continue inserting at the end of the
475 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
476 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
479 Br->eraseFromParent();
481 // Replace all uses of the entry with the predecessor, in case there
482 // are phis in the cleanup.
483 Entry->replaceAllUsesWith(Pred);
486 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
488 // Kill the entry block.
489 Entry->eraseFromParent();
492 CGF.Builder.SetInsertPoint(Pred);
497 static void EmitCleanup(CodeGenFunction &CGF,
498 EHScopeStack::Cleanup *Fn,
499 EHScopeStack::Cleanup::Flags flags,
500 Address ActiveFlag) {
501 // If there's an active flag, load it and skip the cleanup if it's
503 llvm::BasicBlock *ContBB = nullptr;
504 if (ActiveFlag.isValid()) {
505 ContBB = CGF.createBasicBlock("cleanup.done");
506 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
507 llvm::Value *IsActive
508 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
509 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
510 CGF.EmitBlock(CleanupBB);
513 // Ask the cleanup to emit itself.
514 Fn->Emit(CGF, flags);
515 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
517 // Emit the continuation block if there was an active flag.
518 if (ActiveFlag.isValid())
519 CGF.EmitBlock(ContBB);
522 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
523 llvm::BasicBlock *From,
524 llvm::BasicBlock *To) {
525 // Exit is the exit block of a cleanup, so it always terminates in
526 // an unconditional branch or a switch.
527 llvm::TerminatorInst *Term = Exit->getTerminator();
529 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
530 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
531 Br->setSuccessor(0, To);
533 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
534 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
535 if (Switch->getSuccessor(I) == From)
536 Switch->setSuccessor(I, To);
540 /// We don't need a normal entry block for the given cleanup.
541 /// Optimistic fixup branches can cause these blocks to come into
542 /// existence anyway; if so, destroy it.
544 /// The validity of this transformation is very much specific to the
545 /// exact ways in which we form branches to cleanup entries.
546 static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
547 EHCleanupScope &scope) {
548 llvm::BasicBlock *entry = scope.getNormalBlock();
551 // Replace all the uses with unreachable.
552 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
553 for (llvm::BasicBlock::use_iterator
554 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
558 use.set(unreachableBB);
560 // The only uses should be fixup switches.
561 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
562 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
563 // Replace the switch with a branch.
564 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
566 // The switch operand is a load from the cleanup-dest alloca.
567 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
569 // Destroy the switch.
570 si->eraseFromParent();
573 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
574 assert(condition->use_empty());
575 condition->eraseFromParent();
579 assert(entry->use_empty());
583 /// Pops a cleanup block. If the block includes a normal cleanup, the
584 /// current insertion point is threaded through the cleanup, as are
585 /// any branch fixups on the cleanup.
586 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
587 assert(!EHStack.empty() && "cleanup stack is empty!");
588 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
589 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
590 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
592 // Remember activation information.
593 bool IsActive = Scope.isActive();
594 Address NormalActiveFlag =
595 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
596 : Address::invalid();
597 Address EHActiveFlag =
598 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
599 : Address::invalid();
601 // Check whether we need an EH cleanup. This is only true if we've
602 // generated a lazy EH cleanup block.
603 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
604 assert(Scope.hasEHBranches() == (EHEntry != nullptr));
605 bool RequiresEHCleanup = (EHEntry != nullptr);
606 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
608 // Check the three conditions which might require a normal cleanup:
610 // - whether there are branch fix-ups through this cleanup
611 unsigned FixupDepth = Scope.getFixupDepth();
612 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
614 // - whether there are branch-throughs or branch-afters
615 bool HasExistingBranches = Scope.hasBranches();
617 // - whether there's a fallthrough
618 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
619 bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
621 // Branch-through fall-throughs leave the insertion point set to the
622 // end of the last cleanup, which points to the current scope. The
623 // rest of IR gen doesn't need to worry about this; it only happens
624 // during the execution of PopCleanupBlocks().
625 bool HasPrebranchedFallthrough =
626 (FallthroughSource && FallthroughSource->getTerminator());
628 // If this is a normal cleanup, then having a prebranched
629 // fallthrough implies that the fallthrough source unconditionally
631 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
632 (Scope.getNormalBlock() &&
633 FallthroughSource->getTerminator()->getSuccessor(0)
634 == Scope.getNormalBlock()));
636 bool RequiresNormalCleanup = false;
637 if (Scope.isNormalCleanup() &&
638 (HasFixups || HasExistingBranches || HasFallthrough)) {
639 RequiresNormalCleanup = true;
642 // If we have a prebranched fallthrough into an inactive normal
643 // cleanup, rewrite it so that it leads to the appropriate place.
644 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
645 llvm::BasicBlock *prebranchDest;
647 // If the prebranch is semantically branching through the next
648 // cleanup, just forward it to the next block, leaving the
649 // insertion point in the prebranched block.
650 if (FallthroughIsBranchThrough) {
651 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
652 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
654 // Otherwise, we need to make a new block. If the normal cleanup
655 // isn't being used at all, we could actually reuse the normal
656 // entry block, but this is simpler, and it avoids conflicts with
657 // dead optimistic fixup branches.
659 prebranchDest = createBasicBlock("forwarded-prebranch");
660 EmitBlock(prebranchDest);
663 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
664 assert(normalEntry && !normalEntry->use_empty());
666 ForwardPrebranchedFallthrough(FallthroughSource,
667 normalEntry, prebranchDest);
670 // If we don't need the cleanup at all, we're done.
671 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
672 destroyOptimisticNormalEntry(*this, Scope);
673 EHStack.popCleanup(); // safe because there are no fixups
674 assert(EHStack.getNumBranchFixups() == 0 ||
675 EHStack.hasNormalCleanups());
679 // Copy the cleanup emission data out. This uses either a stack
680 // array or malloc'd memory, depending on the size, which is
681 // behavior that SmallVector would provide, if we could use it
682 // here. Unfortunately, if you ask for a SmallVector<char>, the
683 // alignment isn't sufficient.
684 auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
685 llvm::AlignedCharArray<EHScopeStack::ScopeStackAlignment, 8 * sizeof(void *)> CleanupBufferStack;
686 std::unique_ptr<char[]> CleanupBufferHeap;
687 size_t CleanupSize = Scope.getCleanupSize();
688 EHScopeStack::Cleanup *Fn;
690 if (CleanupSize <= sizeof(CleanupBufferStack)) {
691 memcpy(CleanupBufferStack.buffer, CleanupSource, CleanupSize);
692 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack.buffer);
694 CleanupBufferHeap.reset(new char[CleanupSize]);
695 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
696 Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
699 EHScopeStack::Cleanup::Flags cleanupFlags;
700 if (Scope.isNormalCleanup())
701 cleanupFlags.setIsNormalCleanupKind();
702 if (Scope.isEHCleanup())
703 cleanupFlags.setIsEHCleanupKind();
705 if (!RequiresNormalCleanup) {
706 destroyOptimisticNormalEntry(*this, Scope);
707 EHStack.popCleanup();
709 // If we have a fallthrough and no other need for the cleanup,
711 if (HasFallthrough && !HasPrebranchedFallthrough &&
712 !HasFixups && !HasExistingBranches) {
714 destroyOptimisticNormalEntry(*this, Scope);
715 EHStack.popCleanup();
717 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
719 // Otherwise, the best approach is to thread everything through
720 // the cleanup block and then try to clean up after ourselves.
722 // Force the entry block to exist.
723 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
725 // I. Set up the fallthrough edge in.
727 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
729 // If there's a fallthrough, we need to store the cleanup
730 // destination index. For fall-throughs this is always zero.
731 if (HasFallthrough) {
732 if (!HasPrebranchedFallthrough)
733 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
735 // Otherwise, save and clear the IP if we don't have fallthrough
736 // because the cleanup is inactive.
737 } else if (FallthroughSource) {
738 assert(!IsActive && "source without fallthrough for active cleanup");
739 savedInactiveFallthroughIP = Builder.saveAndClearIP();
742 // II. Emit the entry block. This implicitly branches to it if
743 // we have fallthrough. All the fixups and existing branches
744 // should already be branched to it.
745 EmitBlock(NormalEntry);
747 // III. Figure out where we're going and build the cleanup
750 bool HasEnclosingCleanups =
751 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
753 // Compute the branch-through dest if we need it:
754 // - if there are branch-throughs threaded through the scope
755 // - if fall-through is a branch-through
756 // - if there are fixups that will be optimistically forwarded
757 // to the enclosing cleanup
758 llvm::BasicBlock *BranchThroughDest = nullptr;
759 if (Scope.hasBranchThroughs() ||
760 (FallthroughSource && FallthroughIsBranchThrough) ||
761 (HasFixups && HasEnclosingCleanups)) {
762 assert(HasEnclosingCleanups);
763 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
764 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
767 llvm::BasicBlock *FallthroughDest = nullptr;
768 SmallVector<llvm::Instruction*, 2> InstsToAppend;
770 // If there's exactly one branch-after and no other threads,
771 // we can route it without a switch.
772 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
773 Scope.getNumBranchAfters() == 1) {
774 assert(!BranchThroughDest || !IsActive);
776 // Clean up the possibly dead store to the cleanup dest slot.
777 llvm::Instruction *NormalCleanupDestSlot =
778 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
779 if (NormalCleanupDestSlot->hasOneUse()) {
780 NormalCleanupDestSlot->user_back()->eraseFromParent();
781 NormalCleanupDestSlot->eraseFromParent();
782 NormalCleanupDest = nullptr;
785 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
786 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
788 // Build a switch-out if we need it:
789 // - if there are branch-afters threaded through the scope
790 // - if fall-through is a branch-after
791 // - if there are fixups that have nowhere left to go and
792 // so must be immediately resolved
793 } else if (Scope.getNumBranchAfters() ||
794 (HasFallthrough && !FallthroughIsBranchThrough) ||
795 (HasFixups && !HasEnclosingCleanups)) {
797 llvm::BasicBlock *Default =
798 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
800 // TODO: base this on the number of branch-afters and fixups
801 const unsigned SwitchCapacity = 10;
803 llvm::LoadInst *Load =
804 createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
806 llvm::SwitchInst *Switch =
807 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
809 InstsToAppend.push_back(Load);
810 InstsToAppend.push_back(Switch);
812 // Branch-after fallthrough.
813 if (FallthroughSource && !FallthroughIsBranchThrough) {
814 FallthroughDest = createBasicBlock("cleanup.cont");
816 Switch->addCase(Builder.getInt32(0), FallthroughDest);
819 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
820 Switch->addCase(Scope.getBranchAfterIndex(I),
821 Scope.getBranchAfterBlock(I));
824 // If there aren't any enclosing cleanups, we can resolve all
826 if (HasFixups && !HasEnclosingCleanups)
827 ResolveAllBranchFixups(*this, Switch, NormalEntry);
829 // We should always have a branch-through destination in this case.
830 assert(BranchThroughDest);
831 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
834 // IV. Pop the cleanup and emit it.
835 EHStack.popCleanup();
836 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
838 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
840 // Append the prepared cleanup prologue from above.
841 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
842 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
843 NormalExit->getInstList().push_back(InstsToAppend[I]);
845 // Optimistically hope that any fixups will continue falling through.
846 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
848 BranchFixup &Fixup = EHStack.getBranchFixup(I);
849 if (!Fixup.Destination) continue;
850 if (!Fixup.OptimisticBranchBlock) {
851 createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
852 getNormalCleanupDestSlot(),
853 Fixup.InitialBranch);
854 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
856 Fixup.OptimisticBranchBlock = NormalExit;
859 // V. Set up the fallthrough edge out.
861 // Case 1: a fallthrough source exists but doesn't branch to the
862 // cleanup because the cleanup is inactive.
863 if (!HasFallthrough && FallthroughSource) {
864 // Prebranched fallthrough was forwarded earlier.
865 // Non-prebranched fallthrough doesn't need to be forwarded.
866 // Either way, all we need to do is restore the IP we cleared before.
868 Builder.restoreIP(savedInactiveFallthroughIP);
870 // Case 2: a fallthrough source exists and should branch to the
871 // cleanup, but we're not supposed to branch through to the next
873 } else if (HasFallthrough && FallthroughDest) {
874 assert(!FallthroughIsBranchThrough);
875 EmitBlock(FallthroughDest);
877 // Case 3: a fallthrough source exists and should branch to the
878 // cleanup and then through to the next.
879 } else if (HasFallthrough) {
880 // Everything is already set up for this.
882 // Case 4: no fallthrough source exists.
884 Builder.ClearInsertionPoint();
887 // VI. Assorted cleaning.
889 // Check whether we can merge NormalEntry into a single predecessor.
890 // This might invalidate (non-IR) pointers to NormalEntry.
891 llvm::BasicBlock *NewNormalEntry =
892 SimplifyCleanupEntry(*this, NormalEntry);
894 // If it did invalidate those pointers, and NormalEntry was the same
895 // as NormalExit, go back and patch up the fixups.
896 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
897 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
899 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
903 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
905 // Emit the EH cleanup if required.
906 if (RequiresEHCleanup) {
907 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
911 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
913 // Push a terminate scope or cleanupendpad scope around the potentially
914 // throwing cleanups. For funclet EH personalities, the cleanupendpad models
915 // program termination when cleanups throw.
916 bool PushedTerminate = false;
917 SaveAndRestore<llvm::Instruction *> RestoreCurrentFuncletPad(
919 llvm::CleanupPadInst *CPI = nullptr;
920 if (!EHPersonality::get(*this).usesFuncletPads()) {
921 EHStack.pushTerminate();
922 PushedTerminate = true;
924 llvm::Value *ParentPad = CurrentFuncletPad;
926 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
927 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
930 // We only actually emit the cleanup code if the cleanup is either
931 // active or was used before it was deactivated.
932 if (EHActiveFlag.isValid() || IsActive) {
933 cleanupFlags.setIsForEHCleanup();
934 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
938 Builder.CreateCleanupRet(CPI, NextAction);
940 Builder.CreateBr(NextAction);
942 // Leave the terminate scope.
944 EHStack.popTerminate();
946 Builder.restoreIP(SavedIP);
948 SimplifyCleanupEntry(*this, EHEntry);
952 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
953 /// specified destination obviously has no cleanups to run. 'false' is always
954 /// a conservatively correct answer for this method.
955 bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
956 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
957 && "stale jump destination");
959 // Calculate the innermost active normal cleanup.
960 EHScopeStack::stable_iterator TopCleanup =
961 EHStack.getInnermostActiveNormalCleanup();
963 // If we're not in an active normal cleanup scope, or if the
964 // destination scope is within the innermost active normal cleanup
965 // scope, we don't need to worry about fixups.
966 if (TopCleanup == EHStack.stable_end() ||
967 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
970 // Otherwise, we might need some cleanups.
975 /// Terminate the current block by emitting a branch which might leave
976 /// the current cleanup-protected scope. The target scope may not yet
977 /// be known, in which case this will require a fixup.
979 /// As a side-effect, this method clears the insertion point.
980 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
981 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
982 && "stale jump destination");
984 if (!HaveInsertPoint())
987 // Create the branch.
988 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
990 // Calculate the innermost active normal cleanup.
991 EHScopeStack::stable_iterator
992 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
994 // If we're not in an active normal cleanup scope, or if the
995 // destination scope is within the innermost active normal cleanup
996 // scope, we don't need to worry about fixups.
997 if (TopCleanup == EHStack.stable_end() ||
998 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
999 Builder.ClearInsertionPoint();
1003 // If we can't resolve the destination cleanup scope, just add this
1004 // to the current cleanup scope as a branch fixup.
1005 if (!Dest.getScopeDepth().isValid()) {
1006 BranchFixup &Fixup = EHStack.addBranchFixup();
1007 Fixup.Destination = Dest.getBlock();
1008 Fixup.DestinationIndex = Dest.getDestIndex();
1009 Fixup.InitialBranch = BI;
1010 Fixup.OptimisticBranchBlock = nullptr;
1012 Builder.ClearInsertionPoint();
1016 // Otherwise, thread through all the normal cleanups in scope.
1018 // Store the index at the start.
1019 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1020 createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
1022 // Adjust BI to point to the first cleanup block.
1024 EHCleanupScope &Scope =
1025 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1026 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1029 // Add this destination to all the scopes involved.
1030 EHScopeStack::stable_iterator I = TopCleanup;
1031 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1032 if (E.strictlyEncloses(I)) {
1034 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1035 assert(Scope.isNormalCleanup());
1036 I = Scope.getEnclosingNormalCleanup();
1038 // If this is the last cleanup we're propagating through, tell it
1039 // that there's a resolved jump moving through it.
1040 if (!E.strictlyEncloses(I)) {
1041 Scope.addBranchAfter(Index, Dest.getBlock());
1045 // Otherwise, tell the scope that there's a jump propoagating
1046 // through it. If this isn't new information, all the rest of
1047 // the work has been done before.
1048 if (!Scope.addBranchThrough(Dest.getBlock()))
1053 Builder.ClearInsertionPoint();
1056 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1057 EHScopeStack::stable_iterator C) {
1058 // If we needed a normal block for any reason, that counts.
1059 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1062 // Check whether any enclosed cleanups were needed.
1063 for (EHScopeStack::stable_iterator
1064 I = EHStack.getInnermostNormalCleanup();
1066 assert(C.strictlyEncloses(I));
1067 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1068 if (S.getNormalBlock()) return true;
1069 I = S.getEnclosingNormalCleanup();
1075 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1076 EHScopeStack::stable_iterator cleanup) {
1077 // If we needed an EH block for any reason, that counts.
1078 if (EHStack.find(cleanup)->hasEHBranches())
1081 // Check whether any enclosed cleanups were needed.
1082 for (EHScopeStack::stable_iterator
1083 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1084 assert(cleanup.strictlyEncloses(i));
1086 EHScope &scope = *EHStack.find(i);
1087 if (scope.hasEHBranches())
1090 i = scope.getEnclosingEHScope();
1096 enum ForActivation_t {
1101 /// The given cleanup block is changing activation state. Configure a
1102 /// cleanup variable if necessary.
1104 /// It would be good if we had some way of determining if there were
1105 /// extra uses *after* the change-over point.
1106 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1107 EHScopeStack::stable_iterator C,
1108 ForActivation_t kind,
1109 llvm::Instruction *dominatingIP) {
1110 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1112 // We always need the flag if we're activating the cleanup in a
1113 // conditional context, because we have to assume that the current
1114 // location doesn't necessarily dominate the cleanup's code.
1115 bool isActivatedInConditional =
1116 (kind == ForActivation && CGF.isInConditionalBranch());
1118 bool needFlag = false;
1120 // Calculate whether the cleanup was used:
1122 // - as a normal cleanup
1123 if (Scope.isNormalCleanup() &&
1124 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1125 Scope.setTestFlagInNormalCleanup();
1129 // - as an EH cleanup
1130 if (Scope.isEHCleanup() &&
1131 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1132 Scope.setTestFlagInEHCleanup();
1136 // If it hasn't yet been used as either, we're done.
1137 if (!needFlag) return;
1139 Address var = Scope.getActiveFlag();
1140 if (!var.isValid()) {
1141 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1142 "cleanup.isactive");
1143 Scope.setActiveFlag(var);
1145 assert(dominatingIP && "no existing variable and no dominating IP!");
1147 // Initialize to true or false depending on whether it was
1148 // active up to this point.
1149 llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1151 // If we're in a conditional block, ignore the dominating IP and
1152 // use the outermost conditional branch.
1153 if (CGF.isInConditionalBranch()) {
1154 CGF.setBeforeOutermostConditional(value, var);
1156 createStoreInstBefore(value, var, dominatingIP);
1160 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1163 /// Activate a cleanup that was created in an inactivated state.
1164 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1165 llvm::Instruction *dominatingIP) {
1166 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1167 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1168 assert(!Scope.isActive() && "double activation");
1170 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1172 Scope.setActive(true);
1175 /// Deactive a cleanup that was created in an active state.
1176 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1177 llvm::Instruction *dominatingIP) {
1178 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1179 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1180 assert(Scope.isActive() && "double deactivation");
1182 // If it's the top of the stack, just pop it.
1183 if (C == EHStack.stable_begin()) {
1184 // If it's a normal cleanup, we need to pretend that the
1185 // fallthrough is unreachable.
1186 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1188 Builder.restoreIP(SavedIP);
1192 // Otherwise, follow the general case.
1193 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1195 Scope.setActive(false);
1198 Address CodeGenFunction::getNormalCleanupDestSlot() {
1199 if (!NormalCleanupDest)
1201 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1202 return Address(NormalCleanupDest, CharUnits::fromQuantity(4));
1205 /// Emits all the code to cause the given temporary to be cleaned up.
1206 void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1209 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1210 /*useEHCleanup*/ true);