Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGCleanup.cpp
35234 views
//===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains code dealing with the IR generation for cleanups9// and related information.10//11// A "cleanup" is a piece of code which needs to be executed whenever12// control transfers out of a particular scope. This can be13// conditionalized to occur only on exceptional control flow, only on14// normal control flow, or both.15//16//===----------------------------------------------------------------------===//1718#include "CGCleanup.h"19#include "CodeGenFunction.h"20#include "llvm/Support/SaveAndRestore.h"2122using namespace clang;23using namespace CodeGen;2425bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {26if (rv.isScalar())27return DominatingLLVMValue::needsSaving(rv.getScalarVal());28if (rv.isAggregate())29return DominatingValue<Address>::needsSaving(rv.getAggregateAddress());30return true;31}3233DominatingValue<RValue>::saved_type34DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {35if (rv.isScalar()) {36llvm::Value *V = rv.getScalarVal();37return saved_type(DominatingLLVMValue::save(CGF, V),38DominatingLLVMValue::needsSaving(V) ? ScalarAddress39: ScalarLiteral);40}4142if (rv.isComplex()) {43CodeGenFunction::ComplexPairTy V = rv.getComplexVal();44return saved_type(DominatingLLVMValue::save(CGF, V.first),45DominatingLLVMValue::save(CGF, V.second));46}4748assert(rv.isAggregate());49Address V = rv.getAggregateAddress();50return saved_type(DominatingValue<Address>::save(CGF, V),51DominatingValue<Address>::needsSaving(V)52? AggregateAddress53: AggregateLiteral);54}5556/// Given a saved r-value produced by SaveRValue, perform the code57/// necessary to restore it to usability at the current insertion58/// point.59RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {60switch (K) {61case ScalarLiteral:62case ScalarAddress:63return RValue::get(DominatingLLVMValue::restore(CGF, Vals.first));64case AggregateLiteral:65case AggregateAddress:66return RValue::getAggregate(67DominatingValue<Address>::restore(CGF, AggregateAddr));68case ComplexAddress: {69llvm::Value *real = DominatingLLVMValue::restore(CGF, Vals.first);70llvm::Value *imag = DominatingLLVMValue::restore(CGF, Vals.second);71return RValue::getComplex(real, imag);72}73}7475llvm_unreachable("bad saved r-value kind");76}7778/// Push an entry of the given size onto this protected-scope stack.79char *EHScopeStack::allocate(size_t Size) {80Size = llvm::alignTo(Size, ScopeStackAlignment);81if (!StartOfBuffer) {82unsigned Capacity = 1024;83while (Capacity < Size) Capacity *= 2;84StartOfBuffer = new char[Capacity];85StartOfData = EndOfBuffer = StartOfBuffer + Capacity;86} else if (static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {87unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;88unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);8990unsigned NewCapacity = CurrentCapacity;91do {92NewCapacity *= 2;93} while (NewCapacity < UsedCapacity + Size);9495char *NewStartOfBuffer = new char[NewCapacity];96char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;97char *NewStartOfData = NewEndOfBuffer - UsedCapacity;98memcpy(NewStartOfData, StartOfData, UsedCapacity);99delete [] StartOfBuffer;100StartOfBuffer = NewStartOfBuffer;101EndOfBuffer = NewEndOfBuffer;102StartOfData = NewStartOfData;103}104105assert(StartOfBuffer + Size <= StartOfData);106StartOfData -= Size;107return StartOfData;108}109110void EHScopeStack::deallocate(size_t Size) {111StartOfData += llvm::alignTo(Size, ScopeStackAlignment);112}113114bool EHScopeStack::containsOnlyLifetimeMarkers(115EHScopeStack::stable_iterator Old) const {116for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {117EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);118if (!cleanup || !cleanup->isLifetimeMarker())119return false;120}121122return true;123}124125bool EHScopeStack::requiresLandingPad() const {126for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {127// Skip lifetime markers.128if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))129if (cleanup->isLifetimeMarker()) {130si = cleanup->getEnclosingEHScope();131continue;132}133return true;134}135136return false;137}138139EHScopeStack::stable_iterator140EHScopeStack::getInnermostActiveNormalCleanup() const {141for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();142si != se; ) {143EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));144if (cleanup.isActive()) return si;145si = cleanup.getEnclosingNormalCleanup();146}147return stable_end();148}149150151void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {152char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));153bool IsNormalCleanup = Kind & NormalCleanup;154bool IsEHCleanup = Kind & EHCleanup;155bool IsLifetimeMarker = Kind & LifetimeMarker;156157// Per C++ [except.terminate], it is implementation-defined whether none,158// some, or all cleanups are called before std::terminate. Thus, when159// terminate is the current EH scope, we may skip adding any EH cleanup160// scopes.161if (InnermostEHScope != stable_end() &&162find(InnermostEHScope)->getKind() == EHScope::Terminate)163IsEHCleanup = false;164165EHCleanupScope *Scope =166new (Buffer) EHCleanupScope(IsNormalCleanup,167IsEHCleanup,168Size,169BranchFixups.size(),170InnermostNormalCleanup,171InnermostEHScope);172if (IsNormalCleanup)173InnermostNormalCleanup = stable_begin();174if (IsEHCleanup)175InnermostEHScope = stable_begin();176if (IsLifetimeMarker)177Scope->setLifetimeMarker();178179// With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup180// If exceptions are disabled/ignored and SEH is not in use, then there is no181// invoke destination. SEH "works" even if exceptions are off. In practice,182// this means that C++ destructors and other EH cleanups don't run, which is183// consistent with MSVC's behavior, except in the presence of -EHa.184// Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.185if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&186CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())187CGF->EmitSehCppScopeBegin();188189return Scope->getCleanupBuffer();190}191192void EHScopeStack::popCleanup() {193assert(!empty() && "popping exception stack when not empty");194195assert(isa<EHCleanupScope>(*begin()));196EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());197InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();198InnermostEHScope = Cleanup.getEnclosingEHScope();199deallocate(Cleanup.getAllocatedSize());200201// Destroy the cleanup.202Cleanup.Destroy();203204// Check whether we can shrink the branch-fixups stack.205if (!BranchFixups.empty()) {206// If we no longer have any normal cleanups, all the fixups are207// complete.208if (!hasNormalCleanups())209BranchFixups.clear();210211// Otherwise we can still trim out unnecessary nulls.212else213popNullFixups();214}215}216217EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {218assert(getInnermostEHScope() == stable_end());219char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));220EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);221InnermostEHScope = stable_begin();222return filter;223}224225void EHScopeStack::popFilter() {226assert(!empty() && "popping exception stack when not empty");227228EHFilterScope &filter = cast<EHFilterScope>(*begin());229deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));230231InnermostEHScope = filter.getEnclosingEHScope();232}233234EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {235char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));236EHCatchScope *scope =237new (buffer) EHCatchScope(numHandlers, InnermostEHScope);238InnermostEHScope = stable_begin();239return scope;240}241242void EHScopeStack::pushTerminate() {243char *Buffer = allocate(EHTerminateScope::getSize());244new (Buffer) EHTerminateScope(InnermostEHScope);245InnermostEHScope = stable_begin();246}247248/// Remove any 'null' fixups on the stack. However, we can't pop more249/// fixups than the fixup depth on the innermost normal cleanup, or250/// else fixups that we try to add to that cleanup will end up in the251/// wrong place. We *could* try to shrink fixup depths, but that's252/// actually a lot of work for little benefit.253void EHScopeStack::popNullFixups() {254// We expect this to only be called when there's still an innermost255// normal cleanup; otherwise there really shouldn't be any fixups.256assert(hasNormalCleanups());257258EHScopeStack::iterator it = find(InnermostNormalCleanup);259unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();260assert(BranchFixups.size() >= MinSize && "fixup stack out of order");261262while (BranchFixups.size() > MinSize &&263BranchFixups.back().Destination == nullptr)264BranchFixups.pop_back();265}266267RawAddress CodeGenFunction::createCleanupActiveFlag() {268// Create a variable to decide whether the cleanup needs to be run.269RawAddress active = CreateTempAllocaWithoutCast(270Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");271272// Initialize it to false at a site that's guaranteed to be run273// before each evaluation.274setBeforeOutermostConditional(Builder.getFalse(), active, *this);275276// Initialize it to true at the current location.277Builder.CreateStore(Builder.getTrue(), active);278279return active;280}281282void CodeGenFunction::initFullExprCleanupWithFlag(RawAddress ActiveFlag) {283// Set that as the active flag in the cleanup.284EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());285assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");286cleanup.setActiveFlag(ActiveFlag);287288if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();289if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();290}291292void EHScopeStack::Cleanup::anchor() {}293294static void createStoreInstBefore(llvm::Value *value, Address addr,295llvm::Instruction *beforeInst,296CodeGenFunction &CGF) {297auto store = new llvm::StoreInst(value, addr.emitRawPointer(CGF), beforeInst);298store->setAlignment(addr.getAlignment().getAsAlign());299}300301static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,302llvm::Instruction *beforeInst,303CodeGenFunction &CGF) {304return new llvm::LoadInst(addr.getElementType(), addr.emitRawPointer(CGF),305name, false, addr.getAlignment().getAsAlign(),306beforeInst);307}308309/// All the branch fixups on the EH stack have propagated out past the310/// outermost normal cleanup; resolve them all by adding cases to the311/// given switch instruction.312static void ResolveAllBranchFixups(CodeGenFunction &CGF,313llvm::SwitchInst *Switch,314llvm::BasicBlock *CleanupEntry) {315llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;316317for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {318// Skip this fixup if its destination isn't set.319BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);320if (Fixup.Destination == nullptr) continue;321322// If there isn't an OptimisticBranchBlock, then InitialBranch is323// still pointing directly to its destination; forward it to the324// appropriate cleanup entry. This is required in the specific325// case of326// { std::string s; goto lbl; }327// lbl:328// i.e. where there's an unresolved fixup inside a single cleanup329// entry which we're currently popping.330if (Fixup.OptimisticBranchBlock == nullptr) {331createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),332CGF.getNormalCleanupDestSlot(), Fixup.InitialBranch,333CGF);334Fixup.InitialBranch->setSuccessor(0, CleanupEntry);335}336337// Don't add this case to the switch statement twice.338if (!CasesAdded.insert(Fixup.Destination).second)339continue;340341Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),342Fixup.Destination);343}344345CGF.EHStack.clearFixups();346}347348/// Transitions the terminator of the given exit-block of a cleanup to349/// be a cleanup switch.350static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,351llvm::BasicBlock *Block) {352// If it's a branch, turn it into a switch whose default353// destination is its original target.354llvm::Instruction *Term = Block->getTerminator();355assert(Term && "can't transition block without terminator");356357if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {358assert(Br->isUnconditional());359auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),360"cleanup.dest", Term, CGF);361llvm::SwitchInst *Switch =362llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);363Br->eraseFromParent();364return Switch;365} else {366return cast<llvm::SwitchInst>(Term);367}368}369370void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {371assert(Block && "resolving a null target block");372if (!EHStack.getNumBranchFixups()) return;373374assert(EHStack.hasNormalCleanups() &&375"branch fixups exist with no normal cleanups on stack");376377llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;378bool ResolvedAny = false;379380for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {381// Skip this fixup if its destination doesn't match.382BranchFixup &Fixup = EHStack.getBranchFixup(I);383if (Fixup.Destination != Block) continue;384385Fixup.Destination = nullptr;386ResolvedAny = true;387388// If it doesn't have an optimistic branch block, LatestBranch is389// already pointing to the right place.390llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;391if (!BranchBB)392continue;393394// Don't process the same optimistic branch block twice.395if (!ModifiedOptimisticBlocks.insert(BranchBB).second)396continue;397398llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);399400// Add a case to the switch.401Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);402}403404if (ResolvedAny)405EHStack.popNullFixups();406}407408/// Pops cleanup blocks until the given savepoint is reached.409void CodeGenFunction::PopCleanupBlocks(410EHScopeStack::stable_iterator Old,411std::initializer_list<llvm::Value **> ValuesToReload) {412assert(Old.isValid());413414bool HadBranches = false;415while (EHStack.stable_begin() != Old) {416EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());417HadBranches |= Scope.hasBranches();418419// As long as Old strictly encloses the scope's enclosing normal420// cleanup, we're going to emit another normal cleanup which421// fallthrough can propagate through.422bool FallThroughIsBranchThrough =423Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());424425PopCleanupBlock(FallThroughIsBranchThrough);426}427428// If we didn't have any branches, the insertion point before cleanups must429// dominate the current insertion point and we don't need to reload any430// values.431if (!HadBranches)432return;433434// Spill and reload all values that the caller wants to be live at the current435// insertion point.436for (llvm::Value **ReloadedValue : ValuesToReload) {437auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);438if (!Inst)439continue;440441// Don't spill static allocas, they dominate all cleanups. These are created442// by binding a reference to a local variable or temporary.443auto *AI = dyn_cast<llvm::AllocaInst>(Inst);444if (AI && AI->isStaticAlloca())445continue;446447Address Tmp =448CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");449450// Find an insertion point after Inst and spill it to the temporary.451llvm::BasicBlock::iterator InsertBefore;452if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))453InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();454else455InsertBefore = std::next(Inst->getIterator());456CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);457458// Reload the value at the current insertion point.459*ReloadedValue = Builder.CreateLoad(Tmp);460}461}462463/// Pops cleanup blocks until the given savepoint is reached, then add the464/// cleanups from the given savepoint in the lifetime-extended cleanups stack.465void CodeGenFunction::PopCleanupBlocks(466EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,467std::initializer_list<llvm::Value **> ValuesToReload) {468PopCleanupBlocks(Old, ValuesToReload);469470// Move our deferred cleanups onto the EH stack.471for (size_t I = OldLifetimeExtendedSize,472E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {473// Alignment should be guaranteed by the vptrs in the individual cleanups.474assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&475"misaligned cleanup stack entry");476477LifetimeExtendedCleanupHeader &Header =478reinterpret_cast<LifetimeExtendedCleanupHeader&>(479LifetimeExtendedCleanupStack[I]);480I += sizeof(Header);481482EHStack.pushCopyOfCleanup(Header.getKind(),483&LifetimeExtendedCleanupStack[I],484Header.getSize());485I += Header.getSize();486487if (Header.isConditional()) {488RawAddress ActiveFlag =489reinterpret_cast<RawAddress &>(LifetimeExtendedCleanupStack[I]);490initFullExprCleanupWithFlag(ActiveFlag);491I += sizeof(ActiveFlag);492}493}494LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);495}496497static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,498EHCleanupScope &Scope) {499assert(Scope.isNormalCleanup());500llvm::BasicBlock *Entry = Scope.getNormalBlock();501if (!Entry) {502Entry = CGF.createBasicBlock("cleanup");503Scope.setNormalBlock(Entry);504}505return Entry;506}507508/// Attempts to reduce a cleanup's entry block to a fallthrough. This509/// is basically llvm::MergeBlockIntoPredecessor, except510/// simplified/optimized for the tighter constraints on cleanup blocks.511///512/// Returns the new block, whatever it is.513static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,514llvm::BasicBlock *Entry) {515llvm::BasicBlock *Pred = Entry->getSinglePredecessor();516if (!Pred) return Entry;517518llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());519if (!Br || Br->isConditional()) return Entry;520assert(Br->getSuccessor(0) == Entry);521522// If we were previously inserting at the end of the cleanup entry523// block, we'll need to continue inserting at the end of the524// predecessor.525bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;526assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());527528// Kill the branch.529Br->eraseFromParent();530531// Replace all uses of the entry with the predecessor, in case there532// are phis in the cleanup.533Entry->replaceAllUsesWith(Pred);534535// Merge the blocks.536Pred->splice(Pred->end(), Entry);537538// Kill the entry block.539Entry->eraseFromParent();540541if (WasInsertBlock)542CGF.Builder.SetInsertPoint(Pred);543544return Pred;545}546547static void EmitCleanup(CodeGenFunction &CGF,548EHScopeStack::Cleanup *Fn,549EHScopeStack::Cleanup::Flags flags,550Address ActiveFlag) {551// If there's an active flag, load it and skip the cleanup if it's552// false.553llvm::BasicBlock *ContBB = nullptr;554if (ActiveFlag.isValid()) {555ContBB = CGF.createBasicBlock("cleanup.done");556llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");557llvm::Value *IsActive558= CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");559CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);560CGF.EmitBlock(CleanupBB);561}562563// Ask the cleanup to emit itself.564Fn->Emit(CGF, flags);565assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");566567// Emit the continuation block if there was an active flag.568if (ActiveFlag.isValid())569CGF.EmitBlock(ContBB);570}571572static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,573llvm::BasicBlock *From,574llvm::BasicBlock *To) {575// Exit is the exit block of a cleanup, so it always terminates in576// an unconditional branch or a switch.577llvm::Instruction *Term = Exit->getTerminator();578579if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {580assert(Br->isUnconditional() && Br->getSuccessor(0) == From);581Br->setSuccessor(0, To);582} else {583llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);584for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)585if (Switch->getSuccessor(I) == From)586Switch->setSuccessor(I, To);587}588}589590/// We don't need a normal entry block for the given cleanup.591/// Optimistic fixup branches can cause these blocks to come into592/// existence anyway; if so, destroy it.593///594/// The validity of this transformation is very much specific to the595/// exact ways in which we form branches to cleanup entries.596static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,597EHCleanupScope &scope) {598llvm::BasicBlock *entry = scope.getNormalBlock();599if (!entry) return;600601// Replace all the uses with unreachable.602llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();603for (llvm::BasicBlock::use_iterator604i = entry->use_begin(), e = entry->use_end(); i != e; ) {605llvm::Use &use = *i;606++i;607608use.set(unreachableBB);609610// The only uses should be fixup switches.611llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());612if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {613// Replace the switch with a branch.614llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);615616// The switch operand is a load from the cleanup-dest alloca.617llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());618619// Destroy the switch.620si->eraseFromParent();621622// Destroy the load.623assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());624assert(condition->use_empty());625condition->eraseFromParent();626}627}628629assert(entry->use_empty());630delete entry;631}632633/// Pops a cleanup block. If the block includes a normal cleanup, the634/// current insertion point is threaded through the cleanup, as are635/// any branch fixups on the cleanup.636void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,637bool ForDeactivation) {638assert(!EHStack.empty() && "cleanup stack is empty!");639assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");640EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());641assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());642643// If we are deactivating a normal cleanup, we need to pretend that the644// fallthrough is unreachable. We restore this IP before returning.645CGBuilderTy::InsertPoint NormalDeactivateOrigIP;646if (ForDeactivation && (Scope.isNormalCleanup() || !getLangOpts().EHAsynch)) {647NormalDeactivateOrigIP = Builder.saveAndClearIP();648}649// Remember activation information.650bool IsActive = Scope.isActive();651Address NormalActiveFlag =652Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()653: Address::invalid();654Address EHActiveFlag =655Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()656: Address::invalid();657658// Check whether we need an EH cleanup. This is only true if we've659// generated a lazy EH cleanup block.660llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();661assert(Scope.hasEHBranches() == (EHEntry != nullptr));662bool RequiresEHCleanup = (EHEntry != nullptr);663EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();664665// Check the three conditions which might require a normal cleanup:666667// - whether there are branch fix-ups through this cleanup668unsigned FixupDepth = Scope.getFixupDepth();669bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;670671// - whether there are branch-throughs or branch-afters672bool HasExistingBranches = Scope.hasBranches();673674// - whether there's a fallthrough675llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();676bool HasFallthrough =677FallthroughSource != nullptr && (IsActive || HasExistingBranches);678679// Branch-through fall-throughs leave the insertion point set to the680// end of the last cleanup, which points to the current scope. The681// rest of IR gen doesn't need to worry about this; it only happens682// during the execution of PopCleanupBlocks().683bool HasPrebranchedFallthrough =684(FallthroughSource && FallthroughSource->getTerminator());685686// If this is a normal cleanup, then having a prebranched687// fallthrough implies that the fallthrough source unconditionally688// jumps here.689assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||690(Scope.getNormalBlock() &&691FallthroughSource->getTerminator()->getSuccessor(0)692== Scope.getNormalBlock()));693694bool RequiresNormalCleanup = false;695if (Scope.isNormalCleanup() &&696(HasFixups || HasExistingBranches || HasFallthrough)) {697RequiresNormalCleanup = true;698}699700// If we have a prebranched fallthrough into an inactive normal701// cleanup, rewrite it so that it leads to the appropriate place.702if (Scope.isNormalCleanup() && HasPrebranchedFallthrough &&703!RequiresNormalCleanup) {704// FIXME: Come up with a program which would need forwarding prebranched705// fallthrough and add tests. Otherwise delete this and assert against it.706assert(!IsActive);707llvm::BasicBlock *prebranchDest;708709// If the prebranch is semantically branching through the next710// cleanup, just forward it to the next block, leaving the711// insertion point in the prebranched block.712if (FallthroughIsBranchThrough) {713EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());714prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));715716// Otherwise, we need to make a new block. If the normal cleanup717// isn't being used at all, we could actually reuse the normal718// entry block, but this is simpler, and it avoids conflicts with719// dead optimistic fixup branches.720} else {721prebranchDest = createBasicBlock("forwarded-prebranch");722EmitBlock(prebranchDest);723}724725llvm::BasicBlock *normalEntry = Scope.getNormalBlock();726assert(normalEntry && !normalEntry->use_empty());727728ForwardPrebranchedFallthrough(FallthroughSource,729normalEntry, prebranchDest);730}731732// If we don't need the cleanup at all, we're done.733if (!RequiresNormalCleanup && !RequiresEHCleanup) {734destroyOptimisticNormalEntry(*this, Scope);735EHStack.popCleanup(); // safe because there are no fixups736assert(EHStack.getNumBranchFixups() == 0 ||737EHStack.hasNormalCleanups());738if (NormalDeactivateOrigIP.isSet())739Builder.restoreIP(NormalDeactivateOrigIP);740return;741}742743// Copy the cleanup emission data out. This uses either a stack744// array or malloc'd memory, depending on the size, which is745// behavior that SmallVector would provide, if we could use it746// here. Unfortunately, if you ask for a SmallVector<char>, the747// alignment isn't sufficient.748auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());749alignas(EHScopeStack::ScopeStackAlignment) char750CleanupBufferStack[8 * sizeof(void *)];751std::unique_ptr<char[]> CleanupBufferHeap;752size_t CleanupSize = Scope.getCleanupSize();753EHScopeStack::Cleanup *Fn;754755if (CleanupSize <= sizeof(CleanupBufferStack)) {756memcpy(CleanupBufferStack, CleanupSource, CleanupSize);757Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);758} else {759CleanupBufferHeap.reset(new char[CleanupSize]);760memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);761Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());762}763764EHScopeStack::Cleanup::Flags cleanupFlags;765if (Scope.isNormalCleanup())766cleanupFlags.setIsNormalCleanupKind();767if (Scope.isEHCleanup())768cleanupFlags.setIsEHCleanupKind();769770// Under -EHa, invoke seh.scope.end() to mark scope end before dtor771bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();772const EHPersonality &Personality = EHPersonality::get(*this);773if (!RequiresNormalCleanup) {774// Mark CPP scope end for passed-by-value Arg temp775// per Windows ABI which is "normally" Cleanup in callee776if (IsEHa && getInvokeDest()) {777// If we are deactivating a normal cleanup then we don't have a778// fallthrough. Restore original IP to emit CPP scope ends in the correct779// block.780if (NormalDeactivateOrigIP.isSet())781Builder.restoreIP(NormalDeactivateOrigIP);782if (Personality.isMSVCXXPersonality() && Builder.GetInsertBlock())783EmitSehCppScopeEnd();784if (NormalDeactivateOrigIP.isSet())785NormalDeactivateOrigIP = Builder.saveAndClearIP();786}787destroyOptimisticNormalEntry(*this, Scope);788Scope.MarkEmitted();789EHStack.popCleanup();790} else {791// If we have a fallthrough and no other need for the cleanup,792// emit it directly.793if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&794!HasExistingBranches) {795796// mark SEH scope end for fall-through flow797if (IsEHa && getInvokeDest()) {798if (Personality.isMSVCXXPersonality())799EmitSehCppScopeEnd();800else801EmitSehTryScopeEnd();802}803804destroyOptimisticNormalEntry(*this, Scope);805Scope.MarkEmitted();806EHStack.popCleanup();807808EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);809810// Otherwise, the best approach is to thread everything through811// the cleanup block and then try to clean up after ourselves.812} else {813// Force the entry block to exist.814llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);815816// I. Set up the fallthrough edge in.817818CGBuilderTy::InsertPoint savedInactiveFallthroughIP;819820// If there's a fallthrough, we need to store the cleanup821// destination index. For fall-throughs this is always zero.822if (HasFallthrough) {823if (!HasPrebranchedFallthrough)824Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());825826// Otherwise, save and clear the IP if we don't have fallthrough827// because the cleanup is inactive.828} else if (FallthroughSource) {829assert(!IsActive && "source without fallthrough for active cleanup");830savedInactiveFallthroughIP = Builder.saveAndClearIP();831}832833// II. Emit the entry block. This implicitly branches to it if834// we have fallthrough. All the fixups and existing branches835// should already be branched to it.836EmitBlock(NormalEntry);837838// intercept normal cleanup to mark SEH scope end839if (IsEHa && getInvokeDest()) {840if (Personality.isMSVCXXPersonality())841EmitSehCppScopeEnd();842else843EmitSehTryScopeEnd();844}845846// III. Figure out where we're going and build the cleanup847// epilogue.848849bool HasEnclosingCleanups =850(Scope.getEnclosingNormalCleanup() != EHStack.stable_end());851852// Compute the branch-through dest if we need it:853// - if there are branch-throughs threaded through the scope854// - if fall-through is a branch-through855// - if there are fixups that will be optimistically forwarded856// to the enclosing cleanup857llvm::BasicBlock *BranchThroughDest = nullptr;858if (Scope.hasBranchThroughs() ||859(FallthroughSource && FallthroughIsBranchThrough) ||860(HasFixups && HasEnclosingCleanups)) {861assert(HasEnclosingCleanups);862EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());863BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));864}865866llvm::BasicBlock *FallthroughDest = nullptr;867SmallVector<llvm::Instruction*, 2> InstsToAppend;868869// If there's exactly one branch-after and no other threads,870// we can route it without a switch.871// Skip for SEH, since ExitSwitch is used to generate code to indicate872// abnormal termination. (SEH: Except _leave and fall-through at873// the end, all other exits in a _try (return/goto/continue/break)874// are considered as abnormal terminations, using NormalCleanupDestSlot875// to indicate abnormal termination)876if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&877!currentFunctionUsesSEHTry() && Scope.getNumBranchAfters() == 1) {878assert(!BranchThroughDest || !IsActive);879880// Clean up the possibly dead store to the cleanup dest slot.881llvm::Instruction *NormalCleanupDestSlot =882cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());883if (NormalCleanupDestSlot->hasOneUse()) {884NormalCleanupDestSlot->user_back()->eraseFromParent();885NormalCleanupDestSlot->eraseFromParent();886NormalCleanupDest = RawAddress::invalid();887}888889llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);890InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));891892// Build a switch-out if we need it:893// - if there are branch-afters threaded through the scope894// - if fall-through is a branch-after895// - if there are fixups that have nowhere left to go and896// so must be immediately resolved897} else if (Scope.getNumBranchAfters() ||898(HasFallthrough && !FallthroughIsBranchThrough) ||899(HasFixups && !HasEnclosingCleanups)) {900901llvm::BasicBlock *Default =902(BranchThroughDest ? BranchThroughDest : getUnreachableBlock());903904// TODO: base this on the number of branch-afters and fixups905const unsigned SwitchCapacity = 10;906907// pass the abnormal exit flag to Fn (SEH cleanup)908cleanupFlags.setHasExitSwitch();909910llvm::LoadInst *Load = createLoadInstBefore(911getNormalCleanupDestSlot(), "cleanup.dest", nullptr, *this);912llvm::SwitchInst *Switch =913llvm::SwitchInst::Create(Load, Default, SwitchCapacity);914915InstsToAppend.push_back(Load);916InstsToAppend.push_back(Switch);917918// Branch-after fallthrough.919if (FallthroughSource && !FallthroughIsBranchThrough) {920FallthroughDest = createBasicBlock("cleanup.cont");921if (HasFallthrough)922Switch->addCase(Builder.getInt32(0), FallthroughDest);923}924925for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {926Switch->addCase(Scope.getBranchAfterIndex(I),927Scope.getBranchAfterBlock(I));928}929930// If there aren't any enclosing cleanups, we can resolve all931// the fixups now.932if (HasFixups && !HasEnclosingCleanups)933ResolveAllBranchFixups(*this, Switch, NormalEntry);934} else {935// We should always have a branch-through destination in this case.936assert(BranchThroughDest);937InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));938}939940// IV. Pop the cleanup and emit it.941Scope.MarkEmitted();942EHStack.popCleanup();943assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);944945EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);946947// Append the prepared cleanup prologue from above.948llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();949for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)950InstsToAppend[I]->insertInto(NormalExit, NormalExit->end());951952// Optimistically hope that any fixups will continue falling through.953for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();954I < E; ++I) {955BranchFixup &Fixup = EHStack.getBranchFixup(I);956if (!Fixup.Destination) continue;957if (!Fixup.OptimisticBranchBlock) {958createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),959getNormalCleanupDestSlot(), Fixup.InitialBranch,960*this);961Fixup.InitialBranch->setSuccessor(0, NormalEntry);962}963Fixup.OptimisticBranchBlock = NormalExit;964}965966// V. Set up the fallthrough edge out.967968// Case 1: a fallthrough source exists but doesn't branch to the969// cleanup because the cleanup is inactive.970if (!HasFallthrough && FallthroughSource) {971// Prebranched fallthrough was forwarded earlier.972// Non-prebranched fallthrough doesn't need to be forwarded.973// Either way, all we need to do is restore the IP we cleared before.974assert(!IsActive);975Builder.restoreIP(savedInactiveFallthroughIP);976977// Case 2: a fallthrough source exists and should branch to the978// cleanup, but we're not supposed to branch through to the next979// cleanup.980} else if (HasFallthrough && FallthroughDest) {981assert(!FallthroughIsBranchThrough);982EmitBlock(FallthroughDest);983984// Case 3: a fallthrough source exists and should branch to the985// cleanup and then through to the next.986} else if (HasFallthrough) {987// Everything is already set up for this.988989// Case 4: no fallthrough source exists.990} else {991Builder.ClearInsertionPoint();992}993994// VI. Assorted cleaning.995996// Check whether we can merge NormalEntry into a single predecessor.997// This might invalidate (non-IR) pointers to NormalEntry.998llvm::BasicBlock *NewNormalEntry =999SimplifyCleanupEntry(*this, NormalEntry);10001001// If it did invalidate those pointers, and NormalEntry was the same1002// as NormalExit, go back and patch up the fixups.1003if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)1004for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();1005I < E; ++I)1006EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;1007}1008}10091010if (NormalDeactivateOrigIP.isSet())1011Builder.restoreIP(NormalDeactivateOrigIP);1012assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);10131014// Emit the EH cleanup if required.1015if (RequiresEHCleanup) {1016CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();10171018EmitBlock(EHEntry);10191020llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);10211022// Push a terminate scope or cleanupendpad scope around the potentially1023// throwing cleanups. For funclet EH personalities, the cleanupendpad models1024// program termination when cleanups throw.1025bool PushedTerminate = false;1026SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);1027llvm::CleanupPadInst *CPI = nullptr;10281029const EHPersonality &Personality = EHPersonality::get(*this);1030if (Personality.usesFuncletPads()) {1031llvm::Value *ParentPad = CurrentFuncletPad;1032if (!ParentPad)1033ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());1034CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);1035}10361037// Non-MSVC personalities need to terminate when an EH cleanup throws.1038if (!Personality.isMSVCPersonality()) {1039EHStack.pushTerminate();1040PushedTerminate = true;1041} else if (IsEHa && getInvokeDest()) {1042EmitSehCppScopeEnd();1043}10441045// We only actually emit the cleanup code if the cleanup is either1046// active or was used before it was deactivated.1047if (EHActiveFlag.isValid() || IsActive) {1048cleanupFlags.setIsForEHCleanup();1049EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);1050}10511052if (CPI)1053Builder.CreateCleanupRet(CPI, NextAction);1054else1055Builder.CreateBr(NextAction);10561057// Leave the terminate scope.1058if (PushedTerminate)1059EHStack.popTerminate();10601061Builder.restoreIP(SavedIP);10621063SimplifyCleanupEntry(*this, EHEntry);1064}1065}10661067/// isObviouslyBranchWithoutCleanups - Return true if a branch to the1068/// specified destination obviously has no cleanups to run. 'false' is always1069/// a conservatively correct answer for this method.1070bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {1071assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())1072&& "stale jump destination");10731074// Calculate the innermost active normal cleanup.1075EHScopeStack::stable_iterator TopCleanup =1076EHStack.getInnermostActiveNormalCleanup();10771078// If we're not in an active normal cleanup scope, or if the1079// destination scope is within the innermost active normal cleanup1080// scope, we don't need to worry about fixups.1081if (TopCleanup == EHStack.stable_end() ||1082TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid1083return true;10841085// Otherwise, we might need some cleanups.1086return false;1087}108810891090/// Terminate the current block by emitting a branch which might leave1091/// the current cleanup-protected scope. The target scope may not yet1092/// be known, in which case this will require a fixup.1093///1094/// As a side-effect, this method clears the insertion point.1095void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {1096assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())1097&& "stale jump destination");10981099if (!HaveInsertPoint())1100return;11011102// Create the branch.1103llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());11041105// Calculate the innermost active normal cleanup.1106EHScopeStack::stable_iterator1107TopCleanup = EHStack.getInnermostActiveNormalCleanup();11081109// If we're not in an active normal cleanup scope, or if the1110// destination scope is within the innermost active normal cleanup1111// scope, we don't need to worry about fixups.1112if (TopCleanup == EHStack.stable_end() ||1113TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid1114Builder.ClearInsertionPoint();1115return;1116}11171118// If we can't resolve the destination cleanup scope, just add this1119// to the current cleanup scope as a branch fixup.1120if (!Dest.getScopeDepth().isValid()) {1121BranchFixup &Fixup = EHStack.addBranchFixup();1122Fixup.Destination = Dest.getBlock();1123Fixup.DestinationIndex = Dest.getDestIndex();1124Fixup.InitialBranch = BI;1125Fixup.OptimisticBranchBlock = nullptr;11261127Builder.ClearInsertionPoint();1128return;1129}11301131// Otherwise, thread through all the normal cleanups in scope.11321133// Store the index at the start.1134llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());1135createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI, *this);11361137// Adjust BI to point to the first cleanup block.1138{1139EHCleanupScope &Scope =1140cast<EHCleanupScope>(*EHStack.find(TopCleanup));1141BI->setSuccessor(0, CreateNormalEntry(*this, Scope));1142}11431144// Add this destination to all the scopes involved.1145EHScopeStack::stable_iterator I = TopCleanup;1146EHScopeStack::stable_iterator E = Dest.getScopeDepth();1147if (E.strictlyEncloses(I)) {1148while (true) {1149EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));1150assert(Scope.isNormalCleanup());1151I = Scope.getEnclosingNormalCleanup();11521153// If this is the last cleanup we're propagating through, tell it1154// that there's a resolved jump moving through it.1155if (!E.strictlyEncloses(I)) {1156Scope.addBranchAfter(Index, Dest.getBlock());1157break;1158}11591160// Otherwise, tell the scope that there's a jump propagating1161// through it. If this isn't new information, all the rest of1162// the work has been done before.1163if (!Scope.addBranchThrough(Dest.getBlock()))1164break;1165}1166}11671168Builder.ClearInsertionPoint();1169}11701171static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,1172EHScopeStack::stable_iterator cleanup) {1173// If we needed an EH block for any reason, that counts.1174if (EHStack.find(cleanup)->hasEHBranches())1175return true;11761177// Check whether any enclosed cleanups were needed.1178for (EHScopeStack::stable_iterator1179i = EHStack.getInnermostEHScope(); i != cleanup; ) {1180assert(cleanup.strictlyEncloses(i));11811182EHScope &scope = *EHStack.find(i);1183if (scope.hasEHBranches())1184return true;11851186i = scope.getEnclosingEHScope();1187}11881189return false;1190}11911192enum ForActivation_t {1193ForActivation,1194ForDeactivation1195};11961197/// The given cleanup block is changing activation state. Configure a1198/// cleanup variable if necessary.1199///1200/// It would be good if we had some way of determining if there were1201/// extra uses *after* the change-over point.1202static void SetupCleanupBlockActivation(CodeGenFunction &CGF,1203EHScopeStack::stable_iterator C,1204ForActivation_t kind,1205llvm::Instruction *dominatingIP) {1206EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));12071208// We always need the flag if we're activating the cleanup in a1209// conditional context, because we have to assume that the current1210// location doesn't necessarily dominate the cleanup's code.1211bool isActivatedInConditional =1212(kind == ForActivation && CGF.isInConditionalBranch());12131214bool needFlag = false;12151216// Calculate whether the cleanup was used:12171218// - as a normal cleanup1219if (Scope.isNormalCleanup()) {1220Scope.setTestFlagInNormalCleanup();1221needFlag = true;1222}12231224// - as an EH cleanup1225if (Scope.isEHCleanup() &&1226(isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {1227Scope.setTestFlagInEHCleanup();1228needFlag = true;1229}12301231// If it hasn't yet been used as either, we're done.1232if (!needFlag)1233return;12341235Address var = Scope.getActiveFlag();1236if (!var.isValid()) {1237CodeGenFunction::AllocaTrackerRAII AllocaTracker(CGF);1238var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),1239"cleanup.isactive");1240Scope.setActiveFlag(var);1241Scope.AddAuxAllocas(AllocaTracker.Take());12421243assert(dominatingIP && "no existing variable and no dominating IP!");12441245// Initialize to true or false depending on whether it was1246// active up to this point.1247llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);12481249// If we're in a conditional block, ignore the dominating IP and1250// use the outermost conditional branch.1251if (CGF.isInConditionalBranch()) {1252CGF.setBeforeOutermostConditional(value, var, CGF);1253} else {1254createStoreInstBefore(value, var, dominatingIP, CGF);1255}1256}12571258CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);1259}12601261/// Activate a cleanup that was created in an inactivated state.1262void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,1263llvm::Instruction *dominatingIP) {1264assert(C != EHStack.stable_end() && "activating bottom of stack?");1265EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));1266assert(!Scope.isActive() && "double activation");12671268SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);12691270Scope.setActive(true);1271}12721273/// Deactive a cleanup that was created in an active state.1274void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,1275llvm::Instruction *dominatingIP) {1276assert(C != EHStack.stable_end() && "deactivating bottom of stack?");1277EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));1278assert(Scope.isActive() && "double deactivation");12791280// If it's the top of the stack, just pop it, but do so only if it belongs1281// to the current RunCleanupsScope.1282if (C == EHStack.stable_begin() &&1283CurrentCleanupScopeDepth.strictlyEncloses(C)) {1284PopCleanupBlock(/*FallthroughIsBranchThrough=*/false,1285/*ForDeactivation=*/true);1286return;1287}12881289// Otherwise, follow the general case.1290SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);12911292Scope.setActive(false);1293}12941295RawAddress CodeGenFunction::getNormalCleanupDestSlot() {1296if (!NormalCleanupDest.isValid())1297NormalCleanupDest =1298CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");1299return NormalCleanupDest;1300}13011302/// Emits all the code to cause the given temporary to be cleaned up.1303void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,1304QualType TempType,1305Address Ptr) {1306pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,1307/*useEHCleanup*/ true);1308}13091310// Need to set "funclet" in OperandBundle properly for noThrow1311// intrinsic (see CGCall.cpp)1312static void EmitSehScope(CodeGenFunction &CGF,1313llvm::FunctionCallee &SehCppScope) {1314llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();1315assert(CGF.Builder.GetInsertBlock() && InvokeDest);1316llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");1317SmallVector<llvm::OperandBundleDef, 1> BundleList =1318CGF.getBundlesForFunclet(SehCppScope.getCallee());1319if (CGF.CurrentFuncletPad)1320BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);1321CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, std::nullopt,1322BundleList);1323CGF.EmitBlock(Cont);1324}13251326// Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa1327void CodeGenFunction::EmitSehCppScopeBegin() {1328assert(getLangOpts().EHAsynch);1329llvm::FunctionType *FTy =1330llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);1331llvm::FunctionCallee SehCppScope =1332CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.begin");1333EmitSehScope(*this, SehCppScope);1334}13351336// Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa1337// llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"1338void CodeGenFunction::EmitSehCppScopeEnd() {1339assert(getLangOpts().EHAsynch);1340llvm::FunctionType *FTy =1341llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);1342llvm::FunctionCallee SehCppScope =1343CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.end");1344EmitSehScope(*this, SehCppScope);1345}13461347// Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa1348void CodeGenFunction::EmitSehTryScopeBegin() {1349assert(getLangOpts().EHAsynch);1350llvm::FunctionType *FTy =1351llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);1352llvm::FunctionCallee SehCppScope =1353CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");1354EmitSehScope(*this, SehCppScope);1355}13561357// Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa1358void CodeGenFunction::EmitSehTryScopeEnd() {1359assert(getLangOpts().EHAsynch);1360llvm::FunctionType *FTy =1361llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);1362llvm::FunctionCallee SehCppScope =1363CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");1364EmitSehScope(*this, SehCppScope);1365}136613671368