21 #include "llvm/Support/SaveAndRestore.h"
23 using namespace clang;
24 using namespace CodeGen;
41 return saved_type(
V,
nullptr, ScalarLiteral);
47 return saved_type(addr.
getPointer(),
nullptr, ScalarAddress);
52 llvm::Type *ComplexTy =
53 llvm::StructType::get(
V.first->getType(),
V.second->getType());
57 return saved_type(addr.
getPointer(),
nullptr, ComplexAddress);
63 return saved_type(
V.getPointer(),
V.getElementType(), AggregateLiteral,
64 V.getAlignment().getQuantity());
69 return saved_type(addr.
getPointer(),
V.getElementType(), AggregateAddress,
70 V.getAlignment().getQuantity());
77 auto getSavingAddress = [&](llvm::Value *value) {
78 auto *AI = cast<llvm::AllocaInst>(value);
79 return Address(value, AI->getAllocatedType(),
87 case AggregateLiteral:
90 case AggregateAddress: {
95 case ComplexAddress: {
105 llvm_unreachable(
"bad saved r-value kind");
109 char *EHScopeStack::allocate(
size_t Size) {
111 if (!StartOfBuffer) {
112 unsigned Capacity = 1024;
113 while (Capacity < Size) Capacity *= 2;
114 StartOfBuffer =
new char[Capacity];
115 StartOfData = EndOfBuffer = StartOfBuffer + Capacity;
116 }
else if (
static_cast<size_t>(StartOfData - StartOfBuffer) < Size) {
117 unsigned CurrentCapacity = EndOfBuffer - StartOfBuffer;
118 unsigned UsedCapacity = CurrentCapacity - (StartOfData - StartOfBuffer);
120 unsigned NewCapacity = CurrentCapacity;
123 }
while (NewCapacity < UsedCapacity + Size);
125 char *NewStartOfBuffer =
new char[NewCapacity];
126 char *NewEndOfBuffer = NewStartOfBuffer + NewCapacity;
127 char *NewStartOfData = NewEndOfBuffer - UsedCapacity;
128 memcpy(NewStartOfData, StartOfData, UsedCapacity);
129 delete [] StartOfBuffer;
130 StartOfBuffer = NewStartOfBuffer;
131 EndOfBuffer = NewEndOfBuffer;
132 StartOfData = NewStartOfData;
135 assert(StartOfBuffer + Size <= StartOfData);
140 void EHScopeStack::deallocate(
size_t Size) {
158 if (
auto *
cleanup = dyn_cast<EHCleanupScope>(&*
find(si)))
159 if (
cleanup->isLifetimeMarker()) {
160 si =
cleanup->getEnclosingEHScope();
174 if (
cleanup.isActive())
return si;
175 si =
cleanup.getEnclosingNormalCleanup();
200 InnermostNormalCleanup,
206 if (IsLifetimeMarker)
207 Scope->setLifetimeMarker();
210 if (CGF->
getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
214 return Scope->getCleanupBuffer();
218 assert(!
empty() &&
"popping exception stack when not empty");
220 assert(isa<EHCleanupScope>(*
begin()));
222 InnermostNormalCleanup =
Cleanup.getEnclosingNormalCleanup();
223 InnermostEHScope =
Cleanup.getEnclosingEHScope();
224 deallocate(
Cleanup.getAllocatedSize());
230 if (!BranchFixups.empty()) {
234 BranchFixups.clear();
251 assert(!
empty() &&
"popping exception stack when not empty");
262 new (buffer)
EHCatchScope(numHandlers, InnermostEHScope);
284 unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
285 assert(BranchFixups.size() >= MinSize &&
"fixup stack out of order");
287 while (BranchFixups.size() > MinSize &&
288 BranchFixups.back().Destination ==
nullptr)
289 BranchFixups.pop_back();
310 assert(!
cleanup.hasActiveFlag() &&
"cleanup already has active flag?");
311 cleanup.setActiveFlag(ActiveFlag);
313 if (
cleanup.isNormalCleanup())
cleanup.setTestFlagInNormalCleanup();
317 void EHScopeStack::Cleanup::anchor() {}
320 llvm::Instruction *beforeInst) {
321 auto store =
new llvm::StoreInst(value, addr.
getPointer(), beforeInst);
326 llvm::Instruction *beforeInst) {
336 llvm::SwitchInst *Switch,
337 llvm::BasicBlock *CleanupEntry) {
374 llvm::BasicBlock *Block) {
377 llvm::Instruction *Term =
Block->getTerminator();
378 assert(Term &&
"can't transition block without terminator");
380 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
381 assert(Br->isUnconditional());
383 "cleanup.dest", Term);
384 llvm::SwitchInst *
Switch =
385 llvm::SwitchInst::Create(
Load, Br->getSuccessor(0), 4,
Block);
386 Br->eraseFromParent();
389 return cast<llvm::SwitchInst>(Term);
394 assert(
Block &&
"resolving a null target block");
395 if (!EHStack.getNumBranchFixups())
return;
397 assert(EHStack.hasNormalCleanups() &&
398 "branch fixups exist with no normal cleanups on stack");
401 bool ResolvedAny =
false;
403 for (
unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
418 if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
428 EHStack.popNullFixups();
434 std::initializer_list<llvm::Value **> ValuesToReload) {
437 bool HadBranches =
false;
438 while (EHStack.stable_begin() != Old) {
440 HadBranches |=
Scope.hasBranches();
445 bool FallThroughIsBranchThrough =
448 PopCleanupBlock(FallThroughIsBranchThrough);
459 for (llvm::Value **ReloadedValue : ValuesToReload) {
460 auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
466 auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
467 if (AI && AI->isStaticAlloca())
471 CreateDefaultAlignTempAlloca(Inst->getType(),
"tmp.exprcleanup");
474 llvm::BasicBlock::iterator InsertBefore;
475 if (
auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
476 InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
478 InsertBefore = std::next(Inst->getIterator());
482 *ReloadedValue = Builder.CreateLoad(Tmp);
490 std::initializer_list<llvm::Value **> ValuesToReload) {
491 PopCleanupBlocks(Old, ValuesToReload);
494 for (
size_t I = OldLifetimeExtendedSize,
495 E = LifetimeExtendedCleanupStack.size(); I != E; ) {
498 "misaligned cleanup stack entry");
502 LifetimeExtendedCleanupStack[I]);
505 EHStack.pushCopyOfCleanup(Header.
getKind(),
506 &LifetimeExtendedCleanupStack[I],
512 reinterpret_cast<Address &
>(LifetimeExtendedCleanupStack[I]);
513 initFullExprCleanupWithFlag(ActiveFlag);
514 I +=
sizeof(ActiveFlag);
517 LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
522 assert(
Scope.isNormalCleanup());
523 llvm::BasicBlock *Entry =
Scope.getNormalBlock();
526 Scope.setNormalBlock(Entry);
537 llvm::BasicBlock *Entry) {
538 llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
539 if (!Pred)
return Entry;
541 llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
542 if (!Br || Br->isConditional())
return Entry;
543 assert(Br->getSuccessor(0) == Entry);
548 bool WasInsertBlock = CGF.
Builder.GetInsertBlock() == Entry;
549 assert(!WasInsertBlock || CGF.
Builder.GetInsertPoint() == Entry->end());
552 Br->eraseFromParent();
556 Entry->replaceAllUsesWith(Pred);
559 Pred->splice(Pred->end(), Entry);
562 Entry->eraseFromParent();
565 CGF.
Builder.SetInsertPoint(Pred);
576 llvm::BasicBlock *ContBB =
nullptr;
580 llvm::Value *IsActive
582 CGF.
Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
587 Fn->
Emit(CGF, flags);
588 assert(CGF.
HaveInsertPoint() &&
"cleanup ended with no insertion point?");
596 llvm::BasicBlock *From,
597 llvm::BasicBlock *To) {
600 llvm::Instruction *Term = Exit->getTerminator();
602 if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
603 assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
604 Br->setSuccessor(0, To);
606 llvm::SwitchInst *
Switch = cast<llvm::SwitchInst>(Term);
607 for (
unsigned I = 0, E =
Switch->getNumSuccessors(); I != E; ++I)
608 if (
Switch->getSuccessor(I) == From)
609 Switch->setSuccessor(I, To);
626 for (llvm::BasicBlock::use_iterator
627 i = entry->use_begin(), e = entry->use_end(); i != e; ) {
631 use.set(unreachableBB);
634 llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
635 if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
637 llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
640 llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
643 si->eraseFromParent();
647 assert(condition->use_empty());
648 condition->eraseFromParent();
652 assert(entry->use_empty());
660 assert(!EHStack.empty() &&
"cleanup stack is empty!");
661 assert(isa<EHCleanupScope>(*EHStack.begin()) &&
"top not a cleanup!");
663 assert(
Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
666 bool IsActive =
Scope.isActive();
668 Scope.shouldTestFlagInNormalCleanup() ?
Scope.getActiveFlag()
671 Scope.shouldTestFlagInEHCleanup() ?
Scope.getActiveFlag()
676 llvm::BasicBlock *EHEntry =
Scope.getCachedEHDispatchBlock();
677 assert(
Scope.hasEHBranches() == (EHEntry !=
nullptr));
678 bool RequiresEHCleanup = (EHEntry !=
nullptr);
684 unsigned FixupDepth =
Scope.getFixupDepth();
685 bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
688 bool HasExistingBranches =
Scope.hasBranches();
691 llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
692 bool HasFallthrough = (FallthroughSource !=
nullptr && IsActive);
698 bool HasPrebranchedFallthrough =
699 (FallthroughSource && FallthroughSource->getTerminator());
704 assert(!
Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
705 (
Scope.getNormalBlock() &&
706 FallthroughSource->getTerminator()->getSuccessor(0)
707 ==
Scope.getNormalBlock()));
709 bool RequiresNormalCleanup =
false;
710 if (
Scope.isNormalCleanup() &&
711 (HasFixups || HasExistingBranches || HasFallthrough)) {
712 RequiresNormalCleanup =
true;
717 if (
Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
718 llvm::BasicBlock *prebranchDest;
723 if (FallthroughIsBranchThrough) {
724 EHScope &enclosing = *EHStack.find(
Scope.getEnclosingNormalCleanup());
732 prebranchDest = createBasicBlock(
"forwarded-prebranch");
733 EmitBlock(prebranchDest);
736 llvm::BasicBlock *normalEntry =
Scope.getNormalBlock();
737 assert(normalEntry && !normalEntry->use_empty());
740 normalEntry, prebranchDest);
744 if (!RequiresNormalCleanup && !RequiresEHCleanup) {
746 EHStack.popCleanup();
747 assert(EHStack.getNumBranchFixups() == 0 ||
748 EHStack.hasNormalCleanups());
757 auto *CleanupSource =
reinterpret_cast<char *
>(
Scope.getCleanupBuffer());
759 CleanupBufferStack[8 *
sizeof(
void *)];
760 std::unique_ptr<char[]> CleanupBufferHeap;
761 size_t CleanupSize =
Scope.getCleanupSize();
764 if (CleanupSize <=
sizeof(CleanupBufferStack)) {
765 memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
768 CleanupBufferHeap.reset(
new char[CleanupSize]);
769 memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
774 if (
Scope.isNormalCleanup())
776 if (
Scope.isEHCleanup())
780 bool IsEHa = getLangOpts().EHAsynch && !
Scope.isLifetimeMarker();
782 if (!RequiresNormalCleanup) {
785 if (IsEHa && getInvokeDest()) {
787 EmitSehCppScopeEnd();
790 EHStack.popCleanup();
794 if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
795 !HasExistingBranches) {
798 if (IsEHa && getInvokeDest()) {
800 EmitSehCppScopeEnd();
802 EmitSehTryScopeEnd();
806 EHStack.popCleanup();
808 EmitCleanup(*
this, Fn, cleanupFlags, NormalActiveFlag);
818 CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
822 if (HasFallthrough) {
823 if (!HasPrebranchedFallthrough)
824 Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
828 }
else if (FallthroughSource) {
829 assert(!IsActive &&
"source without fallthrough for active cleanup");
830 savedInactiveFallthroughIP = Builder.saveAndClearIP();
836 EmitBlock(NormalEntry);
841 EmitSehCppScopeEnd();
843 EmitSehTryScopeEnd();
849 bool HasEnclosingCleanups =
850 (
Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
857 llvm::BasicBlock *BranchThroughDest =
nullptr;
858 if (
Scope.hasBranchThroughs() ||
859 (FallthroughSource && FallthroughIsBranchThrough) ||
860 (HasFixups && HasEnclosingCleanups)) {
861 assert(HasEnclosingCleanups);
862 EHScope &S = *EHStack.find(
Scope.getEnclosingNormalCleanup());
866 llvm::BasicBlock *FallthroughDest =
nullptr;
871 if (!
Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
872 Scope.getNumBranchAfters() == 1) {
873 assert(!BranchThroughDest || !IsActive);
876 llvm::Instruction *NormalCleanupDestSlot =
877 cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
878 if (NormalCleanupDestSlot->hasOneUse()) {
879 NormalCleanupDestSlot->user_back()->eraseFromParent();
880 NormalCleanupDestSlot->eraseFromParent();
884 llvm::BasicBlock *BranchAfter =
Scope.getBranchAfterBlock(0);
885 InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
892 }
else if (
Scope.getNumBranchAfters() ||
893 (HasFallthrough && !FallthroughIsBranchThrough) ||
894 (HasFixups && !HasEnclosingCleanups)) {
897 (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
900 const unsigned SwitchCapacity = 10;
905 llvm::LoadInst *
Load =
908 llvm::SwitchInst *
Switch =
909 llvm::SwitchInst::Create(
Load,
Default, SwitchCapacity);
911 InstsToAppend.push_back(
Load);
912 InstsToAppend.push_back(
Switch);
915 if (FallthroughSource && !FallthroughIsBranchThrough) {
916 FallthroughDest = createBasicBlock(
"cleanup.cont");
918 Switch->addCase(Builder.getInt32(0), FallthroughDest);
921 for (
unsigned I = 0, E =
Scope.getNumBranchAfters(); I != E; ++I) {
923 Scope.getBranchAfterBlock(I));
928 if (HasFixups && !HasEnclosingCleanups)
932 assert(BranchThroughDest);
933 InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
937 EHStack.popCleanup();
938 assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
940 EmitCleanup(*
this, Fn, cleanupFlags, NormalActiveFlag);
943 llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
944 for (
unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
945 InstsToAppend[I]->insertInto(NormalExit, NormalExit->end());
948 for (
unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
954 getNormalCleanupDestSlot(),
965 if (!HasFallthrough && FallthroughSource) {
970 Builder.restoreIP(savedInactiveFallthroughIP);
975 }
else if (HasFallthrough && FallthroughDest) {
976 assert(!FallthroughIsBranchThrough);
977 EmitBlock(FallthroughDest);
981 }
else if (HasFallthrough) {
986 Builder.ClearInsertionPoint();
993 llvm::BasicBlock *NewNormalEntry =
998 if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
999 for (
unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1001 EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
1005 assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1008 if (RequiresEHCleanup) {
1009 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1013 llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
1018 bool PushedTerminate =
false;
1020 llvm::CleanupPadInst *CPI =
nullptr;
1024 llvm::Value *ParentPad = CurrentFuncletPad;
1026 ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1027 CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
1032 EHStack.pushTerminate();
1033 PushedTerminate =
true;
1038 if (EHActiveFlag.
isValid() || IsActive) {
1040 EmitCleanup(*
this, Fn, cleanupFlags, EHActiveFlag);
1044 Builder.CreateCleanupRet(CPI, NextAction);
1046 Builder.CreateBr(NextAction);
1049 if (PushedTerminate)
1050 EHStack.popTerminate();
1052 Builder.restoreIP(SavedIP);
1063 &&
"stale jump destination");
1067 EHStack.getInnermostActiveNormalCleanup();
1072 if (TopCleanup == EHStack.stable_end() ||
1088 &&
"stale jump destination");
1090 if (!HaveInsertPoint())
1094 llvm::BranchInst *BI = Builder.CreateBr(Dest.
getBlock());
1098 TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1103 if (TopCleanup == EHStack.stable_end() ||
1105 Builder.ClearInsertionPoint();
1118 Builder.ClearInsertionPoint();
1125 llvm::ConstantInt *Index = Builder.getInt32(Dest.
getDestIndex());
1131 cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1141 assert(
Scope.isNormalCleanup());
1142 I =
Scope.getEnclosingNormalCleanup();
1159 Builder.ClearInsertionPoint();
1165 if (cast<EHCleanupScope>(*EHStack.
find(C)).getNormalBlock())
1172 assert(C.strictlyEncloses(I));
1174 if (S.getNormalBlock())
return true;
1175 I = S.getEnclosingNormalCleanup();
1190 assert(
cleanup.strictlyEncloses(i));
1215 llvm::Instruction *dominatingIP) {
1221 bool isActivatedInConditional =
1224 bool needFlag =
false;
1229 if (
Scope.isNormalCleanup() &&
1231 Scope.setTestFlagInNormalCleanup();
1236 if (
Scope.isEHCleanup() &&
1238 Scope.setTestFlagInEHCleanup();
1243 if (!needFlag)
return;
1246 if (!
var.isValid()) {
1248 "cleanup.isactive");
1251 assert(dominatingIP &&
"no existing variable and no dominating IP!");
1271 llvm::Instruction *dominatingIP) {
1272 assert(C != EHStack.stable_end() &&
"activating bottom of stack?");
1274 assert(!
Scope.isActive() &&
"double activation");
1278 Scope.setActive(
true);
1283 llvm::Instruction *dominatingIP) {
1284 assert(C != EHStack.stable_end() &&
"deactivating bottom of stack?");
1286 assert(
Scope.isActive() &&
"double deactivation");
1290 if (C == EHStack.stable_begin() &&
1291 CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1294 if (!
Scope.isNormalCleanup() && getLangOpts().EHAsynch) {
1299 CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1301 Builder.restoreIP(SavedIP);
1309 Scope.setActive(
false);
1313 if (!NormalCleanupDest.isValid())
1315 CreateDefaultAlignTempAlloca(Builder.getInt32Ty(),
"cleanup.dest.slot");
1316 return NormalCleanupDest;
1330 llvm::FunctionCallee &SehCppScope) {
1332 assert(CGF.
Builder.GetInsertBlock() && InvokeDest);
1338 CGF.
Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, std::nullopt,
1345 assert(getLangOpts().EHAsynch);
1346 llvm::FunctionType *FTy =
1347 llvm::FunctionType::get(CGM.VoidTy,
false);
1348 llvm::FunctionCallee SehCppScope =
1349 CGM.CreateRuntimeFunction(FTy,
"llvm.seh.scope.begin");
1356 assert(getLangOpts().EHAsynch);
1357 llvm::FunctionType *FTy =
1358 llvm::FunctionType::get(CGM.VoidTy,
false);
1359 llvm::FunctionCallee SehCppScope =
1360 CGM.CreateRuntimeFunction(FTy,
"llvm.seh.scope.end");
1366 assert(getLangOpts().EHAsynch);
1367 llvm::FunctionType *FTy =
1368 llvm::FunctionType::get(CGM.VoidTy,
false);
1369 llvm::FunctionCallee SehCppScope =
1370 CGM.CreateRuntimeFunction(FTy,
"llvm.seh.try.begin");
1376 assert(getLangOpts().EHAsynch);
1377 llvm::FunctionType *FTy =
1378 llvm::FunctionType::get(CGM.VoidTy,
false);
1379 llvm::FunctionCallee SehCppScope =
1380 CGM.CreateRuntimeFunction(FTy,
"llvm.seh.try.end");