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 "CodeGenFunction.h"
21 #include "CGCleanup.h"
23 using namespace clang;
24 using namespace CodeGen;
26 bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
28 return DominatingLLVMValue::needsSaving(rv.getScalarVal());
30 return DominatingLLVMValue::needsSaving(rv.getAggregateAddr());
34 DominatingValue<RValue>::saved_type
35 DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
37 llvm::Value *V = rv.getScalarVal();
39 // These automatically dominate and don't need to be saved.
40 if (!DominatingLLVMValue::needsSaving(V))
41 return saved_type(V, ScalarLiteral);
43 // Everything else needs an alloca.
44 llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
45 CGF.Builder.CreateStore(V, addr);
46 return saved_type(addr, ScalarAddress);
50 CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
51 llvm::Type *ComplexTy =
52 llvm::StructType::get(V.first->getType(), V.second->getType(),
54 llvm::Value *addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
55 CGF.Builder.CreateStore(V.first, CGF.Builder.CreateStructGEP(addr, 0));
56 CGF.Builder.CreateStore(V.second, CGF.Builder.CreateStructGEP(addr, 1));
57 return saved_type(addr, ComplexAddress);
60 assert(rv.isAggregate());
61 llvm::Value *V = rv.getAggregateAddr(); // TODO: volatile?
62 if (!DominatingLLVMValue::needsSaving(V))
63 return saved_type(V, AggregateLiteral);
65 llvm::Value *addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
66 CGF.Builder.CreateStore(V, addr);
67 return saved_type(addr, AggregateAddress);
70 /// Given a saved r-value produced by SaveRValue, perform the code
71 /// necessary to restore it to usability at the current insertion
73 RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
76 return RValue::get(Value);
78 return RValue::get(CGF.Builder.CreateLoad(Value));
79 case AggregateLiteral:
80 return RValue::getAggregate(Value);
81 case AggregateAddress:
82 return RValue::getAggregate(CGF.Builder.CreateLoad(Value));
83 case ComplexAddress: {
85 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 0));
87 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(Value, 1));
88 return RValue::getComplex(real, imag);
92 llvm_unreachable("bad saved r-value kind");
95 /// Push an entry of the given size onto this protected-scope stack.
96 char *EHScopeStack::allocate(size_t Size) {
98 unsigned Capacity = 1024;
99 while (Capacity < Size) Capacity *= 2;
100 StartOfBuffer = new char[Capacity];
101 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
102 } else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
103 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
104 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
106 unsigned NewCapacity = CurrentCapacity;
109 } while (NewCapacity < UsedCapacity + Size);
111 char *NewStartOfBuffer = new char[NewCapacity];
112 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
113 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
114 memcpy(NewStartOfData, StartOfData, UsedCapacity);
115 delete [] StartOfBuffer;
116 StartOfBuffer = NewStartOfBuffer;
117 EndOfBuffer = NewEndOfBuffer;
118 StartOfData = NewStartOfData;
121 assert(StartOfBuffer + Size <= StartOfData);
126 EHScopeStack::stable_iterator
127 EHScopeStack::getInnermostActiveNormalCleanup() const {
128 for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
130 EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
131 if (cleanup.isActive()) return si;
132 si = cleanup.getEnclosingNormalCleanup();
137 EHScopeStack::stable_iterator EHScopeStack::getInnermostActiveEHScope() const {
138 for (stable_iterator si = getInnermostEHScope(), se = stable_end();
140 // Skip over inactive cleanups.
141 EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*find(si));
142 if (cleanup && !cleanup->isActive()) {
143 si = cleanup->getEnclosingEHScope();
147 // All other scopes are always active.
155 void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
156 assert(((Size % sizeof(void*)) == 0) && "cleanup type is misaligned");
157 char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
158 bool IsNormalCleanup = Kind & NormalCleanup;
159 bool IsEHCleanup = Kind & EHCleanup;
160 bool IsActive = !(Kind & InactiveCleanup);
161 EHCleanupScope *Scope =
162 new (Buffer) EHCleanupScope(IsNormalCleanup,
167 InnermostNormalCleanup,
170 InnermostNormalCleanup = stable_begin();
172 InnermostEHScope = stable_begin();
174 return Scope->getCleanupBuffer();
177 void EHScopeStack::popCleanup() {
178 assert(!empty() && "popping exception stack when not empty");
180 assert(isa<EHCleanupScope>(*begin()));
181 EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
182 InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
183 InnermostEHScope = Cleanup.getEnclosingEHScope();
184 StartOfData += Cleanup.getAllocatedSize();
186 // Destroy the cleanup.
187 Cleanup.~EHCleanupScope();
189 // Check whether we can shrink the branch-fixups stack.
190 if (!BranchFixups.empty()) {
191 // If we no longer have any normal cleanups, all the fixups are
193 if (!hasNormalCleanups())
194 BranchFixups.clear();
196 // Otherwise we can still trim out unnecessary nulls.
202 EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
203 assert(getInnermostEHScope() == stable_end());
204 char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
205 EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
206 InnermostEHScope = stable_begin();
210 void EHScopeStack::popFilter() {
211 assert(!empty() && "popping exception stack when not empty");
213 EHFilterScope &filter = cast<EHFilterScope>(*begin());
214 StartOfData += EHFilterScope::getSizeForNumFilters(filter.getNumFilters());
216 InnermostEHScope = filter.getEnclosingEHScope();
219 EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
220 char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
221 EHCatchScope *scope =
222 new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
223 InnermostEHScope = stable_begin();
227 void EHScopeStack::pushTerminate() {
228 char *Buffer = allocate(EHTerminateScope::getSize());
229 new (Buffer) EHTerminateScope(InnermostEHScope);
230 InnermostEHScope = stable_begin();
233 /// Remove any 'null' fixups on the stack. However, we can't pop more
234 /// fixups than the fixup depth on the innermost normal cleanup, or
235 /// else fixups that we try to add to that cleanup will end up in the
236 /// wrong place. We *could* try to shrink fixup depths, but that's
237 /// actually a lot of work for little benefit.
238 void EHScopeStack::popNullFixups() {
239 // We expect this to only be called when there's still an innermost
240 // normal cleanup; otherwise there really shouldn't be any fixups.
241 assert(hasNormalCleanups());
243 EHScopeStack::iterator it = find(InnermostNormalCleanup);
244 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
245 assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
247 while (BranchFixups.size() > MinSize &&
248 BranchFixups.back().Destination == 0)
249 BranchFixups.pop_back();
252 void CodeGenFunction::initFullExprCleanup() {
253 // Create a variable to decide whether the cleanup needs to be run.
254 llvm::AllocaInst *active
255 = CreateTempAlloca(Builder.getInt1Ty(), "cleanup.cond");
257 // Initialize it to false at a site that's guaranteed to be run
258 // before each evaluation.
259 setBeforeOutermostConditional(Builder.getFalse(), active);
261 // Initialize it to true at the current location.
262 Builder.CreateStore(Builder.getTrue(), active);
264 // Set that as the active flag in the cleanup.
265 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
266 assert(cleanup.getActiveFlag() == 0 && "cleanup already has active flag?");
267 cleanup.setActiveFlag(active);
269 if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
270 if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
273 void EHScopeStack::Cleanup::anchor() {}
275 /// All the branch fixups on the EH stack have propagated out past the
276 /// outermost normal cleanup; resolve them all by adding cases to the
277 /// given switch instruction.
278 static void ResolveAllBranchFixups(CodeGenFunction &CGF,
279 llvm::SwitchInst *Switch,
280 llvm::BasicBlock *CleanupEntry) {
281 llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
283 for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
284 // Skip this fixup if its destination isn't set.
285 BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
286 if (Fixup.Destination == 0) continue;
288 // If there isn't an OptimisticBranchBlock, then InitialBranch is
289 // still pointing directly to its destination; forward it to the
290 // appropriate cleanup entry. This is required in the specific
292 // { std::string s; goto lbl; }
294 // i.e. where there's an unresolved fixup inside a single cleanup
295 // entry which we're currently popping.
296 if (Fixup.OptimisticBranchBlock == 0) {
297 new llvm::StoreInst(CGF.Builder.getInt32(Fixup.DestinationIndex),
298 CGF.getNormalCleanupDestSlot(),
299 Fixup.InitialBranch);
300 Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
303 // Don't add this case to the switch statement twice.
304 if (!CasesAdded.insert(Fixup.Destination)) continue;
306 Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
310 CGF.EHStack.clearFixups();
313 /// Transitions the terminator of the given exit-block of a cleanup to
314 /// be a cleanup switch.
315 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
316 llvm::BasicBlock *Block) {
317 // If it's a branch, turn it into a switch whose default
318 // destination is its original target.
319 llvm::TerminatorInst *Term = Block->getTerminator();
320 assert(Term && "can't transition block without terminator");
322 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
323 assert(Br->isUnconditional());
324 llvm::LoadInst *Load =
325 new llvm::LoadInst(CGF.getNormalCleanupDestSlot(), "cleanup.dest", Term);
326 llvm::SwitchInst *Switch =
327 llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
328 Br->eraseFromParent();
331 return cast<llvm::SwitchInst>(Term);
335 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
336 assert(Block && "resolving a null target block");
337 if (!EHStack.getNumBranchFixups()) return;
339 assert(EHStack.hasNormalCleanups() &&
340 "branch fixups exist with no normal cleanups on stack");
342 llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
343 bool ResolvedAny = false;
345 for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
346 // Skip this fixup if its destination doesn't match.
347 BranchFixup &Fixup = EHStack.getBranchFixup(I);
348 if (Fixup.Destination != Block) continue;
350 Fixup.Destination = 0;
353 // If it doesn't have an optimistic branch block, LatestBranch is
354 // already pointing to the right place.
355 llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
359 // Don't process the same optimistic branch block twice.
360 if (!ModifiedOptimisticBlocks.insert(BranchBB))
363 llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
365 // Add a case to the switch.
366 Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
370 EHStack.popNullFixups();
373 /// Pops cleanup blocks until the given savepoint is reached.
374 void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
375 SourceLocation EHLoc) {
376 assert(Old.isValid());
378 while (EHStack.stable_begin() != Old) {
379 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
381 // As long as Old strictly encloses the scope's enclosing normal
382 // cleanup, we're going to emit another normal cleanup which
383 // fallthrough can propagate through.
384 bool FallThroughIsBranchThrough =
385 Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
387 PopCleanupBlock(FallThroughIsBranchThrough, EHLoc);
391 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
392 EHCleanupScope &Scope) {
393 assert(Scope.isNormalCleanup());
394 llvm::BasicBlock *Entry = Scope.getNormalBlock();
396 Entry = CGF.createBasicBlock("cleanup");
397 Scope.setNormalBlock(Entry);
402 /// Attempts to reduce a cleanup's entry block to a fallthrough. This
403 /// is basically llvm::MergeBlockIntoPredecessor, except
404 /// simplified/optimized for the tighter constraints on cleanup blocks.
406 /// Returns the new block, whatever it is.
407 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
408 llvm::BasicBlock *Entry) {
409 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
410 if (!Pred) return Entry;
412 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
413 if (!Br || Br->isConditional()) return Entry;
414 assert(Br->getSuccessor(0) == Entry);
416 // If we were previously inserting at the end of the cleanup entry
417 // block, we'll need to continue inserting at the end of the
419 bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
420 assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
423 Br->eraseFromParent();
425 // Replace all uses of the entry with the predecessor, in case there
426 // are phis in the cleanup.
427 Entry->replaceAllUsesWith(Pred);
430 Pred->getInstList().splice(Pred->end(), Entry->getInstList());
432 // Kill the entry block.
433 Entry->eraseFromParent();
436 CGF.Builder.SetInsertPoint(Pred);
441 static void EmitCleanup(CodeGenFunction &CGF,
442 EHScopeStack::Cleanup *Fn,
443 EHScopeStack::Cleanup::Flags flags,
444 llvm::Value *ActiveFlag) {
445 // EH cleanups always occur within a terminate scope.
446 if (flags.isForEHCleanup()) CGF.EHStack.pushTerminate();
448 // If there's an active flag, load it and skip the cleanup if it's
450 llvm::BasicBlock *ContBB = 0;
452 ContBB = CGF.createBasicBlock("cleanup.done");
453 llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
454 llvm::Value *IsActive
455 = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
456 CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
457 CGF.EmitBlock(CleanupBB);
460 // Ask the cleanup to emit itself.
461 Fn->Emit(CGF, flags);
462 assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
464 // Emit the continuation block if there was an active flag.
466 CGF.EmitBlock(ContBB);
468 // Leave the terminate scope.
469 if (flags.isForEHCleanup()) CGF.EHStack.popTerminate();
472 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
473 llvm::BasicBlock *From,
474 llvm::BasicBlock *To) {
475 // Exit is the exit block of a cleanup, so it always terminates in
476 // an unconditional branch or a switch.
477 llvm::TerminatorInst *Term = Exit->getTerminator();
479 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
480 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
481 Br->setSuccessor(0, To);
483 llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
484 for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
485 if (Switch->getSuccessor(I) == From)
486 Switch->setSuccessor(I, To);
490 /// We don't need a normal entry block for the given cleanup.
491 /// Optimistic fixup branches can cause these blocks to come into
492 /// existence anyway; if so, destroy it.
494 /// The validity of this transformation is very much specific to the
495 /// exact ways in which we form branches to cleanup entries.
496 static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
497 EHCleanupScope &scope) {
498 llvm::BasicBlock *entry = scope.getNormalBlock();
501 // Replace all the uses with unreachable.
502 llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
503 for (llvm::BasicBlock::use_iterator
504 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
505 llvm::Use &use = i.getUse();
508 use.set(unreachableBB);
510 // The only uses should be fixup switches.
511 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
512 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
513 // Replace the switch with a branch.
514 llvm::BranchInst::Create(si->case_begin().getCaseSuccessor(), si);
516 // The switch operand is a load from the cleanup-dest alloca.
517 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
519 // Destroy the switch.
520 si->eraseFromParent();
523 assert(condition->getOperand(0) == CGF.NormalCleanupDest);
524 assert(condition->use_empty());
525 condition->eraseFromParent();
529 assert(entry->use_empty());
533 /// Pops a cleanup block. If the block includes a normal cleanup, the
534 /// current insertion point is threaded through the cleanup, as are
535 /// any branch fixups on the cleanup.
536 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
537 SourceLocation EHLoc) {
538 assert(!EHStack.empty() && "cleanup stack is empty!");
539 assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
540 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
541 assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
543 // Remember activation information.
544 bool IsActive = Scope.isActive();
545 llvm::Value *NormalActiveFlag =
546 Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag() : 0;
547 llvm::Value *EHActiveFlag =
548 Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag() : 0;
550 // Check whether we need an EH cleanup. This is only true if we've
551 // generated a lazy EH cleanup block.
552 llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
553 assert(Scope.hasEHBranches() == (EHEntry != 0));
554 bool RequiresEHCleanup = (EHEntry != 0);
555 EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
557 // Check the three conditions which might require a normal cleanup:
559 // - whether there are branch fix-ups through this cleanup
560 unsigned FixupDepth = Scope.getFixupDepth();
561 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
563 // - whether there are branch-throughs or branch-afters
564 bool HasExistingBranches = Scope.hasBranches();
566 // - whether there's a fallthrough
567 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
568 bool HasFallthrough = (FallthroughSource != 0 && IsActive);
570 // Branch-through fall-throughs leave the insertion point set to the
571 // end of the last cleanup, which points to the current scope. The
572 // rest of IR gen doesn't need to worry about this; it only happens
573 // during the execution of PopCleanupBlocks().
574 bool HasPrebranchedFallthrough =
575 (FallthroughSource && FallthroughSource->getTerminator());
577 // If this is a normal cleanup, then having a prebranched
578 // fallthrough implies that the fallthrough source unconditionally
580 assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
581 (Scope.getNormalBlock() &&
582 FallthroughSource->getTerminator()->getSuccessor(0)
583 == Scope.getNormalBlock()));
585 bool RequiresNormalCleanup = false;
586 if (Scope.isNormalCleanup() &&
587 (HasFixups || HasExistingBranches || HasFallthrough)) {
588 RequiresNormalCleanup = true;
591 // If we have a prebranched fallthrough into an inactive normal
592 // cleanup, rewrite it so that it leads to the appropriate place.
593 if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
594 llvm::BasicBlock *prebranchDest;
596 // If the prebranch is semantically branching through the next
597 // cleanup, just forward it to the next block, leaving the
598 // insertion point in the prebranched block.
599 if (FallthroughIsBranchThrough) {
600 EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
601 prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
603 // Otherwise, we need to make a new block. If the normal cleanup
604 // isn't being used at all, we could actually reuse the normal
605 // entry block, but this is simpler, and it avoids conflicts with
606 // dead optimistic fixup branches.
608 prebranchDest = createBasicBlock("forwarded-prebranch");
609 EmitBlock(prebranchDest);
612 llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
613 assert(normalEntry && !normalEntry->use_empty());
615 ForwardPrebranchedFallthrough(FallthroughSource,
616 normalEntry, prebranchDest);
619 // If we don't need the cleanup at all, we're done.
620 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
621 destroyOptimisticNormalEntry(*this, Scope);
622 EHStack.popCleanup(); // safe because there are no fixups
623 assert(EHStack.getNumBranchFixups() == 0 ||
624 EHStack.hasNormalCleanups());
628 // Copy the cleanup emission data out. Note that SmallVector
629 // guarantees maximal alignment for its buffer regardless of its
631 SmallVector<char, 8*sizeof(void*)> CleanupBuffer;
632 CleanupBuffer.reserve(Scope.getCleanupSize());
633 memcpy(CleanupBuffer.data(),
634 Scope.getCleanupBuffer(), Scope.getCleanupSize());
635 CleanupBuffer.set_size(Scope.getCleanupSize());
636 EHScopeStack::Cleanup *Fn =
637 reinterpret_cast<EHScopeStack::Cleanup*>(CleanupBuffer.data());
639 EHScopeStack::Cleanup::Flags cleanupFlags;
640 if (Scope.isNormalCleanup())
641 cleanupFlags.setIsNormalCleanupKind();
642 if (Scope.isEHCleanup())
643 cleanupFlags.setIsEHCleanupKind();
645 if (!RequiresNormalCleanup) {
646 destroyOptimisticNormalEntry(*this, Scope);
647 EHStack.popCleanup();
649 // If we have a fallthrough and no other need for the cleanup,
651 if (HasFallthrough && !HasPrebranchedFallthrough &&
652 !HasFixups && !HasExistingBranches) {
654 destroyOptimisticNormalEntry(*this, Scope);
655 EHStack.popCleanup();
657 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
659 // Otherwise, the best approach is to thread everything through
660 // the cleanup block and then try to clean up after ourselves.
662 // Force the entry block to exist.
663 llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
665 // I. Set up the fallthrough edge in.
667 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
669 // If there's a fallthrough, we need to store the cleanup
670 // destination index. For fall-throughs this is always zero.
671 if (HasFallthrough) {
672 if (!HasPrebranchedFallthrough)
673 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
675 // Otherwise, save and clear the IP if we don't have fallthrough
676 // because the cleanup is inactive.
677 } else if (FallthroughSource) {
678 assert(!IsActive && "source without fallthrough for active cleanup");
679 savedInactiveFallthroughIP = Builder.saveAndClearIP();
682 // II. Emit the entry block. This implicitly branches to it if
683 // we have fallthrough. All the fixups and existing branches
684 // should already be branched to it.
685 EmitBlock(NormalEntry);
687 // III. Figure out where we're going and build the cleanup
690 bool HasEnclosingCleanups =
691 (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
693 // Compute the branch-through dest if we need it:
694 // - if there are branch-throughs threaded through the scope
695 // - if fall-through is a branch-through
696 // - if there are fixups that will be optimistically forwarded
697 // to the enclosing cleanup
698 llvm::BasicBlock *BranchThroughDest = 0;
699 if (Scope.hasBranchThroughs() ||
700 (FallthroughSource && FallthroughIsBranchThrough) ||
701 (HasFixups && HasEnclosingCleanups)) {
702 assert(HasEnclosingCleanups);
703 EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
704 BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
707 llvm::BasicBlock *FallthroughDest = 0;
708 SmallVector<llvm::Instruction*, 2> InstsToAppend;
710 // If there's exactly one branch-after and no other threads,
711 // we can route it without a switch.
712 if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
713 Scope.getNumBranchAfters() == 1) {
714 assert(!BranchThroughDest || !IsActive);
716 // TODO: clean up the possibly dead stores to the cleanup dest slot.
717 llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
718 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
720 // Build a switch-out if we need it:
721 // - if there are branch-afters threaded through the scope
722 // - if fall-through is a branch-after
723 // - if there are fixups that have nowhere left to go and
724 // so must be immediately resolved
725 } else if (Scope.getNumBranchAfters() ||
726 (HasFallthrough && !FallthroughIsBranchThrough) ||
727 (HasFixups && !HasEnclosingCleanups)) {
729 llvm::BasicBlock *Default =
730 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
732 // TODO: base this on the number of branch-afters and fixups
733 const unsigned SwitchCapacity = 10;
735 llvm::LoadInst *Load =
736 new llvm::LoadInst(getNormalCleanupDestSlot(), "cleanup.dest");
737 llvm::SwitchInst *Switch =
738 llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
740 InstsToAppend.push_back(Load);
741 InstsToAppend.push_back(Switch);
743 // Branch-after fallthrough.
744 if (FallthroughSource && !FallthroughIsBranchThrough) {
745 FallthroughDest = createBasicBlock("cleanup.cont");
747 Switch->addCase(Builder.getInt32(0), FallthroughDest);
750 for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
751 Switch->addCase(Scope.getBranchAfterIndex(I),
752 Scope.getBranchAfterBlock(I));
755 // If there aren't any enclosing cleanups, we can resolve all
757 if (HasFixups && !HasEnclosingCleanups)
758 ResolveAllBranchFixups(*this, Switch, NormalEntry);
760 // We should always have a branch-through destination in this case.
761 assert(BranchThroughDest);
762 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
765 // IV. Pop the cleanup and emit it.
766 EHStack.popCleanup();
767 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
769 EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
771 // Append the prepared cleanup prologue from above.
772 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
773 for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
774 NormalExit->getInstList().push_back(InstsToAppend[I]);
776 // Optimistically hope that any fixups will continue falling through.
777 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
779 BranchFixup &Fixup = EHStack.getBranchFixup(I);
780 if (!Fixup.Destination) continue;
781 if (!Fixup.OptimisticBranchBlock) {
782 new llvm::StoreInst(Builder.getInt32(Fixup.DestinationIndex),
783 getNormalCleanupDestSlot(),
784 Fixup.InitialBranch);
785 Fixup.InitialBranch->setSuccessor(0, NormalEntry);
787 Fixup.OptimisticBranchBlock = NormalExit;
790 // V. Set up the fallthrough edge out.
792 // Case 1: a fallthrough source exists but doesn't branch to the
793 // cleanup because the cleanup is inactive.
794 if (!HasFallthrough && FallthroughSource) {
795 // Prebranched fallthrough was forwarded earlier.
796 // Non-prebranched fallthrough doesn't need to be forwarded.
797 // Either way, all we need to do is restore the IP we cleared before.
799 Builder.restoreIP(savedInactiveFallthroughIP);
801 // Case 2: a fallthrough source exists and should branch to the
802 // cleanup, but we're not supposed to branch through to the next
804 } else if (HasFallthrough && FallthroughDest) {
805 assert(!FallthroughIsBranchThrough);
806 EmitBlock(FallthroughDest);
808 // Case 3: a fallthrough source exists and should branch to the
809 // cleanup and then through to the next.
810 } else if (HasFallthrough) {
811 // Everything is already set up for this.
813 // Case 4: no fallthrough source exists.
815 Builder.ClearInsertionPoint();
818 // VI. Assorted cleaning.
820 // Check whether we can merge NormalEntry into a single predecessor.
821 // This might invalidate (non-IR) pointers to NormalEntry.
822 llvm::BasicBlock *NewNormalEntry =
823 SimplifyCleanupEntry(*this, NormalEntry);
825 // If it did invalidate those pointers, and NormalEntry was the same
826 // as NormalExit, go back and patch up the fixups.
827 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
828 for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
830 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
834 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
836 // Emit the EH cleanup if required.
837 if (RequiresEHCleanup) {
838 if (CGDebugInfo *DI = getDebugInfo())
839 DI->EmitLocation(Builder, EHLoc);
841 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
845 // We only actually emit the cleanup code if the cleanup is either
846 // active or was used before it was deactivated.
847 if (EHActiveFlag || IsActive) {
849 cleanupFlags.setIsForEHCleanup();
850 EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
853 Builder.CreateBr(getEHDispatchBlock(EHParent));
855 Builder.restoreIP(SavedIP);
857 SimplifyCleanupEntry(*this, EHEntry);
861 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
862 /// specified destination obviously has no cleanups to run. 'false' is always
863 /// a conservatively correct answer for this method.
864 bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
865 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
866 && "stale jump destination");
868 // Calculate the innermost active normal cleanup.
869 EHScopeStack::stable_iterator TopCleanup =
870 EHStack.getInnermostActiveNormalCleanup();
872 // If we're not in an active normal cleanup scope, or if the
873 // destination scope is within the innermost active normal cleanup
874 // scope, we don't need to worry about fixups.
875 if (TopCleanup == EHStack.stable_end() ||
876 TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
879 // Otherwise, we might need some cleanups.
884 /// Terminate the current block by emitting a branch which might leave
885 /// the current cleanup-protected scope. The target scope may not yet
886 /// be known, in which case this will require a fixup.
888 /// As a side-effect, this method clears the insertion point.
889 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
890 assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
891 && "stale jump destination");
893 if (!HaveInsertPoint())
896 // Create the branch.
897 llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
899 // Calculate the innermost active normal cleanup.
900 EHScopeStack::stable_iterator
901 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
903 // If we're not in an active normal cleanup scope, or if the
904 // destination scope is within the innermost active normal cleanup
905 // scope, we don't need to worry about fixups.
906 if (TopCleanup == EHStack.stable_end() ||
907 TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
908 Builder.ClearInsertionPoint();
912 // If we can't resolve the destination cleanup scope, just add this
913 // to the current cleanup scope as a branch fixup.
914 if (!Dest.getScopeDepth().isValid()) {
915 BranchFixup &Fixup = EHStack.addBranchFixup();
916 Fixup.Destination = Dest.getBlock();
917 Fixup.DestinationIndex = Dest.getDestIndex();
918 Fixup.InitialBranch = BI;
919 Fixup.OptimisticBranchBlock = 0;
921 Builder.ClearInsertionPoint();
925 // Otherwise, thread through all the normal cleanups in scope.
927 // Store the index at the start.
928 llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
929 new llvm::StoreInst(Index, getNormalCleanupDestSlot(), BI);
931 // Adjust BI to point to the first cleanup block.
933 EHCleanupScope &Scope =
934 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
935 BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
938 // Add this destination to all the scopes involved.
939 EHScopeStack::stable_iterator I = TopCleanup;
940 EHScopeStack::stable_iterator E = Dest.getScopeDepth();
941 if (E.strictlyEncloses(I)) {
943 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
944 assert(Scope.isNormalCleanup());
945 I = Scope.getEnclosingNormalCleanup();
947 // If this is the last cleanup we're propagating through, tell it
948 // that there's a resolved jump moving through it.
949 if (!E.strictlyEncloses(I)) {
950 Scope.addBranchAfter(Index, Dest.getBlock());
954 // Otherwise, tell the scope that there's a jump propoagating
955 // through it. If this isn't new information, all the rest of
956 // the work has been done before.
957 if (!Scope.addBranchThrough(Dest.getBlock()))
962 Builder.ClearInsertionPoint();
965 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
966 EHScopeStack::stable_iterator C) {
967 // If we needed a normal block for any reason, that counts.
968 if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
971 // Check whether any enclosed cleanups were needed.
972 for (EHScopeStack::stable_iterator
973 I = EHStack.getInnermostNormalCleanup();
975 assert(C.strictlyEncloses(I));
976 EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
977 if (S.getNormalBlock()) return true;
978 I = S.getEnclosingNormalCleanup();
984 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
985 EHScopeStack::stable_iterator cleanup) {
986 // If we needed an EH block for any reason, that counts.
987 if (EHStack.find(cleanup)->hasEHBranches())
990 // Check whether any enclosed cleanups were needed.
991 for (EHScopeStack::stable_iterator
992 i = EHStack.getInnermostEHScope(); i != cleanup; ) {
993 assert(cleanup.strictlyEncloses(i));
995 EHScope &scope = *EHStack.find(i);
996 if (scope.hasEHBranches())
999 i = scope.getEnclosingEHScope();
1005 enum ForActivation_t {
1010 /// The given cleanup block is changing activation state. Configure a
1011 /// cleanup variable if necessary.
1013 /// It would be good if we had some way of determining if there were
1014 /// extra uses *after* the change-over point.
1015 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1016 EHScopeStack::stable_iterator C,
1017 ForActivation_t kind,
1018 llvm::Instruction *dominatingIP) {
1019 EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1021 // We always need the flag if we're activating the cleanup in a
1022 // conditional context, because we have to assume that the current
1023 // location doesn't necessarily dominate the cleanup's code.
1024 bool isActivatedInConditional =
1025 (kind == ForActivation && CGF.isInConditionalBranch());
1027 bool needFlag = false;
1029 // Calculate whether the cleanup was used:
1031 // - as a normal cleanup
1032 if (Scope.isNormalCleanup() &&
1033 (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1034 Scope.setTestFlagInNormalCleanup();
1038 // - as an EH cleanup
1039 if (Scope.isEHCleanup() &&
1040 (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1041 Scope.setTestFlagInEHCleanup();
1045 // If it hasn't yet been used as either, we're done.
1046 if (!needFlag) return;
1048 llvm::AllocaInst *var = Scope.getActiveFlag();
1050 var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), "cleanup.isactive");
1051 Scope.setActiveFlag(var);
1053 assert(dominatingIP && "no existing variable and no dominating IP!");
1055 // Initialize to true or false depending on whether it was
1056 // active up to this point.
1057 llvm::Value *value = CGF.Builder.getInt1(kind == ForDeactivation);
1059 // If we're in a conditional block, ignore the dominating IP and
1060 // use the outermost conditional branch.
1061 if (CGF.isInConditionalBranch()) {
1062 CGF.setBeforeOutermostConditional(value, var);
1064 new llvm::StoreInst(value, var, dominatingIP);
1068 CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1071 /// Activate a cleanup that was created in an inactivated state.
1072 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1073 llvm::Instruction *dominatingIP) {
1074 assert(C != EHStack.stable_end() && "activating bottom of stack?");
1075 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1076 assert(!Scope.isActive() && "double activation");
1078 SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1080 Scope.setActive(true);
1083 /// Deactive a cleanup that was created in an active state.
1084 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1085 llvm::Instruction *dominatingIP) {
1086 assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1087 EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1088 assert(Scope.isActive() && "double deactivation");
1090 // If it's the top of the stack, just pop it.
1091 if (C == EHStack.stable_begin()) {
1092 // If it's a normal cleanup, we need to pretend that the
1093 // fallthrough is unreachable.
1094 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1096 Builder.restoreIP(SavedIP);
1100 // Otherwise, follow the general case.
1101 SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1103 Scope.setActive(false);
1106 llvm::Value *CodeGenFunction::getNormalCleanupDestSlot() {
1107 if (!NormalCleanupDest)
1109 CreateTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1110 return NormalCleanupDest;
1113 /// Emits all the code to cause the given temporary to be cleaned up.
1114 void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1117 pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1118 /*useEHCleanup*/ true);