xref: /llvm-project/clang/lib/CodeGen/CGCleanup.cpp (revision 33e3b2c46084bc47ef4067ed487b24b58934d044)
1 //===--- CGCleanup.cpp - Bookkeeping and code emission for cleanups -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains code dealing with the IR generation for cleanups
10 // and related information.
11 //
12 // A "cleanup" is a piece of code which needs to be executed whenever
13 // control transfers out of a particular scope.  This can be
14 // conditionalized to occur only on exceptional control flow, only on
15 // normal control flow, or both.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "CGCleanup.h"
20 #include "CodeGenFunction.h"
21 #include "llvm/Support/SaveAndRestore.h"
22 
23 using namespace clang;
24 using namespace CodeGen;
25 
26 bool DominatingValue<RValue>::saved_type::needsSaving(RValue rv) {
27   if (rv.isScalar())
28     return DominatingLLVMValue::needsSaving(rv.getScalarVal());
29   if (rv.isAggregate())
30     return DominatingLLVMValue::needsSaving(rv.getAggregatePointer());
31   return true;
32 }
33 
34 DominatingValue<RValue>::saved_type
35 DominatingValue<RValue>::saved_type::save(CodeGenFunction &CGF, RValue rv) {
36   if (rv.isScalar()) {
37     llvm::Value *V = rv.getScalarVal();
38 
39     // These automatically dominate and don't need to be saved.
40     if (!DominatingLLVMValue::needsSaving(V))
41       return saved_type(V, nullptr, ScalarLiteral);
42 
43     // Everything else needs an alloca.
44     Address addr =
45       CGF.CreateDefaultAlignTempAlloca(V->getType(), "saved-rvalue");
46     CGF.Builder.CreateStore(V, addr);
47     return saved_type(addr.getPointer(), nullptr, ScalarAddress);
48   }
49 
50   if (rv.isComplex()) {
51     CodeGenFunction::ComplexPairTy V = rv.getComplexVal();
52     llvm::Type *ComplexTy =
53         llvm::StructType::get(V.first->getType(), V.second->getType());
54     Address addr = CGF.CreateDefaultAlignTempAlloca(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.getPointer(), nullptr, ComplexAddress);
58   }
59 
60   assert(rv.isAggregate());
61   Address V = rv.getAggregateAddress(); // TODO: volatile?
62   if (!DominatingLLVMValue::needsSaving(V.getPointer()))
63     return saved_type(V.getPointer(), V.getElementType(), AggregateLiteral,
64                       V.getAlignment().getQuantity());
65 
66   Address addr =
67     CGF.CreateTempAlloca(V.getType(), CGF.getPointerAlign(), "saved-rvalue");
68   CGF.Builder.CreateStore(V.getPointer(), addr);
69   return saved_type(addr.getPointer(), V.getElementType(), AggregateAddress,
70                     V.getAlignment().getQuantity());
71 }
72 
73 /// Given a saved r-value produced by SaveRValue, perform the code
74 /// necessary to restore it to usability at the current insertion
75 /// point.
76 RValue DominatingValue<RValue>::saved_type::restore(CodeGenFunction &CGF) {
77   auto getSavingAddress = [&](llvm::Value *value) {
78     auto *AI = cast<llvm::AllocaInst>(value);
79     return Address(value, AI->getAllocatedType(),
80                    CharUnits::fromQuantity(AI->getAlign().value()));
81   };
82   switch (K) {
83   case ScalarLiteral:
84     return RValue::get(Value);
85   case ScalarAddress:
86     return RValue::get(CGF.Builder.CreateLoad(getSavingAddress(Value)));
87   case AggregateLiteral:
88     return RValue::getAggregate(
89         Address(Value, ElementType, CharUnits::fromQuantity(Align)));
90   case AggregateAddress: {
91     auto addr = CGF.Builder.CreateLoad(getSavingAddress(Value));
92     return RValue::getAggregate(
93         Address(addr, ElementType, CharUnits::fromQuantity(Align)));
94   }
95   case ComplexAddress: {
96     Address address = getSavingAddress(Value);
97     llvm::Value *real =
98         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 0));
99     llvm::Value *imag =
100         CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(address, 1));
101     return RValue::getComplex(real, imag);
102   }
103   }
104 
105   llvm_unreachable("bad saved r-value kind");
106 }
107 
108 /// Push an entry of the given size onto this protected-scope stack.
109 char *EHScopeStack::allocate(size_t Size) {
110   Size = llvm::alignTo(Size, ScopeStackAlignment);
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);
119 
120     unsigned NewCapacity = CurrentCapacity;
121     do {
122       NewCapacity *= 2;
123     } while (NewCapacity < UsedCapacity + Size);
124 
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;
133   }
134 
135   assert(StartOfBuffer + Size <= StartOfData);
136   StartOfData -= Size;
137   return StartOfData;
138 }
139 
140 void EHScopeStack::deallocate(size_t Size) {
141   StartOfData += llvm::alignTo(Size, ScopeStackAlignment);
142 }
143 
144 bool EHScopeStack::containsOnlyLifetimeMarkers(
145     EHScopeStack::stable_iterator Old) const {
146   for (EHScopeStack::iterator it = begin(); stabilize(it) != Old; it++) {
147     EHCleanupScope *cleanup = dyn_cast<EHCleanupScope>(&*it);
148     if (!cleanup || !cleanup->isLifetimeMarker())
149       return false;
150   }
151 
152   return true;
153 }
154 
155 bool EHScopeStack::requiresLandingPad() const {
156   for (stable_iterator si = getInnermostEHScope(); si != stable_end(); ) {
157     // Skip lifetime markers.
158     if (auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si)))
159       if (cleanup->isLifetimeMarker()) {
160         si = cleanup->getEnclosingEHScope();
161         continue;
162       }
163     return true;
164   }
165 
166   return false;
167 }
168 
169 EHScopeStack::stable_iterator
170 EHScopeStack::getInnermostActiveNormalCleanup() const {
171   for (stable_iterator si = getInnermostNormalCleanup(), se = stable_end();
172          si != se; ) {
173     EHCleanupScope &cleanup = cast<EHCleanupScope>(*find(si));
174     if (cleanup.isActive()) return si;
175     si = cleanup.getEnclosingNormalCleanup();
176   }
177   return stable_end();
178 }
179 
180 
181 void *EHScopeStack::pushCleanup(CleanupKind Kind, size_t Size) {
182   char *Buffer = allocate(EHCleanupScope::getSizeForCleanupSize(Size));
183   bool IsNormalCleanup = Kind & NormalCleanup;
184   bool IsEHCleanup = Kind & EHCleanup;
185   bool IsLifetimeMarker = Kind & LifetimeMarker;
186 
187   // Per C++ [except.terminate], it is implementation-defined whether none,
188   // some, or all cleanups are called before std::terminate. Thus, when
189   // terminate is the current EH scope, we may skip adding any EH cleanup
190   // scopes.
191   if (InnermostEHScope != stable_end() &&
192       find(InnermostEHScope)->getKind() == EHScope::Terminate)
193     IsEHCleanup = false;
194 
195   EHCleanupScope *Scope =
196     new (Buffer) EHCleanupScope(IsNormalCleanup,
197                                 IsEHCleanup,
198                                 Size,
199                                 BranchFixups.size(),
200                                 InnermostNormalCleanup,
201                                 InnermostEHScope);
202   if (IsNormalCleanup)
203     InnermostNormalCleanup = stable_begin();
204   if (IsEHCleanup)
205     InnermostEHScope = stable_begin();
206   if (IsLifetimeMarker)
207     Scope->setLifetimeMarker();
208 
209   // With Windows -EHa, Invoke llvm.seh.scope.begin() for EHCleanup
210   // If exceptions are disabled/ignored and SEH is not in use, then there is no
211   // invoke destination. SEH "works" even if exceptions are off. In practice,
212   // this means that C++ destructors and other EH cleanups don't run, which is
213   // consistent with MSVC's behavior, except in the presence of -EHa.
214   // Check getInvokeDest() to generate llvm.seh.scope.begin() as needed.
215   if (CGF->getLangOpts().EHAsynch && IsEHCleanup && !IsLifetimeMarker &&
216       CGF->getTarget().getCXXABI().isMicrosoft() && CGF->getInvokeDest())
217     CGF->EmitSehCppScopeBegin();
218 
219   return Scope->getCleanupBuffer();
220 }
221 
222 void EHScopeStack::popCleanup() {
223   assert(!empty() && "popping exception stack when not empty");
224 
225   assert(isa<EHCleanupScope>(*begin()));
226   EHCleanupScope &Cleanup = cast<EHCleanupScope>(*begin());
227   InnermostNormalCleanup = Cleanup.getEnclosingNormalCleanup();
228   InnermostEHScope = Cleanup.getEnclosingEHScope();
229   deallocate(Cleanup.getAllocatedSize());
230 
231   // Destroy the cleanup.
232   Cleanup.Destroy();
233 
234   // Check whether we can shrink the branch-fixups stack.
235   if (!BranchFixups.empty()) {
236     // If we no longer have any normal cleanups, all the fixups are
237     // complete.
238     if (!hasNormalCleanups())
239       BranchFixups.clear();
240 
241     // Otherwise we can still trim out unnecessary nulls.
242     else
243       popNullFixups();
244   }
245 }
246 
247 EHFilterScope *EHScopeStack::pushFilter(unsigned numFilters) {
248   assert(getInnermostEHScope() == stable_end());
249   char *buffer = allocate(EHFilterScope::getSizeForNumFilters(numFilters));
250   EHFilterScope *filter = new (buffer) EHFilterScope(numFilters);
251   InnermostEHScope = stable_begin();
252   return filter;
253 }
254 
255 void EHScopeStack::popFilter() {
256   assert(!empty() && "popping exception stack when not empty");
257 
258   EHFilterScope &filter = cast<EHFilterScope>(*begin());
259   deallocate(EHFilterScope::getSizeForNumFilters(filter.getNumFilters()));
260 
261   InnermostEHScope = filter.getEnclosingEHScope();
262 }
263 
264 EHCatchScope *EHScopeStack::pushCatch(unsigned numHandlers) {
265   char *buffer = allocate(EHCatchScope::getSizeForNumHandlers(numHandlers));
266   EHCatchScope *scope =
267     new (buffer) EHCatchScope(numHandlers, InnermostEHScope);
268   InnermostEHScope = stable_begin();
269   return scope;
270 }
271 
272 void EHScopeStack::pushTerminate() {
273   char *Buffer = allocate(EHTerminateScope::getSize());
274   new (Buffer) EHTerminateScope(InnermostEHScope);
275   InnermostEHScope = stable_begin();
276 }
277 
278 /// Remove any 'null' fixups on the stack.  However, we can't pop more
279 /// fixups than the fixup depth on the innermost normal cleanup, or
280 /// else fixups that we try to add to that cleanup will end up in the
281 /// wrong place.  We *could* try to shrink fixup depths, but that's
282 /// actually a lot of work for little benefit.
283 void EHScopeStack::popNullFixups() {
284   // We expect this to only be called when there's still an innermost
285   // normal cleanup;  otherwise there really shouldn't be any fixups.
286   assert(hasNormalCleanups());
287 
288   EHScopeStack::iterator it = find(InnermostNormalCleanup);
289   unsigned MinSize = cast<EHCleanupScope>(*it).getFixupDepth();
290   assert(BranchFixups.size() >= MinSize && "fixup stack out of order");
291 
292   while (BranchFixups.size() > MinSize &&
293          BranchFixups.back().Destination == nullptr)
294     BranchFixups.pop_back();
295 }
296 
297 Address CodeGenFunction::createCleanupActiveFlag() {
298   // Create a variable to decide whether the cleanup needs to be run.
299   Address active = CreateTempAllocaWithoutCast(
300       Builder.getInt1Ty(), CharUnits::One(), "cleanup.cond");
301 
302   // Initialize it to false at a site that's guaranteed to be run
303   // before each evaluation.
304   setBeforeOutermostConditional(Builder.getFalse(), active);
305 
306   // Initialize it to true at the current location.
307   Builder.CreateStore(Builder.getTrue(), active);
308 
309   return active;
310 }
311 
312 void CodeGenFunction::initFullExprCleanupWithFlag(Address ActiveFlag) {
313   // Set that as the active flag in the cleanup.
314   EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
315   assert(!cleanup.hasActiveFlag() && "cleanup already has active flag?");
316   cleanup.setActiveFlag(ActiveFlag);
317 
318   if (cleanup.isNormalCleanup()) cleanup.setTestFlagInNormalCleanup();
319   if (cleanup.isEHCleanup()) cleanup.setTestFlagInEHCleanup();
320 }
321 
322 void EHScopeStack::Cleanup::anchor() {}
323 
324 static void createStoreInstBefore(llvm::Value *value, Address addr,
325                                   llvm::Instruction *beforeInst) {
326   auto store = new llvm::StoreInst(value, addr.getPointer(), beforeInst);
327   store->setAlignment(addr.getAlignment().getAsAlign());
328 }
329 
330 static llvm::LoadInst *createLoadInstBefore(Address addr, const Twine &name,
331                                             llvm::Instruction *beforeInst) {
332   return new llvm::LoadInst(addr.getElementType(), addr.getPointer(), name,
333                             false, addr.getAlignment().getAsAlign(),
334                             beforeInst);
335 }
336 
337 /// All the branch fixups on the EH stack have propagated out past the
338 /// outermost normal cleanup; resolve them all by adding cases to the
339 /// given switch instruction.
340 static void ResolveAllBranchFixups(CodeGenFunction &CGF,
341                                    llvm::SwitchInst *Switch,
342                                    llvm::BasicBlock *CleanupEntry) {
343   llvm::SmallPtrSet<llvm::BasicBlock*, 4> CasesAdded;
344 
345   for (unsigned I = 0, E = CGF.EHStack.getNumBranchFixups(); I != E; ++I) {
346     // Skip this fixup if its destination isn't set.
347     BranchFixup &Fixup = CGF.EHStack.getBranchFixup(I);
348     if (Fixup.Destination == nullptr) continue;
349 
350     // If there isn't an OptimisticBranchBlock, then InitialBranch is
351     // still pointing directly to its destination; forward it to the
352     // appropriate cleanup entry.  This is required in the specific
353     // case of
354     //   { std::string s; goto lbl; }
355     //   lbl:
356     // i.e. where there's an unresolved fixup inside a single cleanup
357     // entry which we're currently popping.
358     if (Fixup.OptimisticBranchBlock == nullptr) {
359       createStoreInstBefore(CGF.Builder.getInt32(Fixup.DestinationIndex),
360                             CGF.getNormalCleanupDestSlot(),
361                             Fixup.InitialBranch);
362       Fixup.InitialBranch->setSuccessor(0, CleanupEntry);
363     }
364 
365     // Don't add this case to the switch statement twice.
366     if (!CasesAdded.insert(Fixup.Destination).second)
367       continue;
368 
369     Switch->addCase(CGF.Builder.getInt32(Fixup.DestinationIndex),
370                     Fixup.Destination);
371   }
372 
373   CGF.EHStack.clearFixups();
374 }
375 
376 /// Transitions the terminator of the given exit-block of a cleanup to
377 /// be a cleanup switch.
378 static llvm::SwitchInst *TransitionToCleanupSwitch(CodeGenFunction &CGF,
379                                                    llvm::BasicBlock *Block) {
380   // If it's a branch, turn it into a switch whose default
381   // destination is its original target.
382   llvm::Instruction *Term = Block->getTerminator();
383   assert(Term && "can't transition block without terminator");
384 
385   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
386     assert(Br->isUnconditional());
387     auto Load = createLoadInstBefore(CGF.getNormalCleanupDestSlot(),
388                                      "cleanup.dest", Term);
389     llvm::SwitchInst *Switch =
390       llvm::SwitchInst::Create(Load, Br->getSuccessor(0), 4, Block);
391     Br->eraseFromParent();
392     return Switch;
393   } else {
394     return cast<llvm::SwitchInst>(Term);
395   }
396 }
397 
398 void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
399   assert(Block && "resolving a null target block");
400   if (!EHStack.getNumBranchFixups()) return;
401 
402   assert(EHStack.hasNormalCleanups() &&
403          "branch fixups exist with no normal cleanups on stack");
404 
405   llvm::SmallPtrSet<llvm::BasicBlock*, 4> ModifiedOptimisticBlocks;
406   bool ResolvedAny = false;
407 
408   for (unsigned I = 0, E = EHStack.getNumBranchFixups(); I != E; ++I) {
409     // Skip this fixup if its destination doesn't match.
410     BranchFixup &Fixup = EHStack.getBranchFixup(I);
411     if (Fixup.Destination != Block) continue;
412 
413     Fixup.Destination = nullptr;
414     ResolvedAny = true;
415 
416     // If it doesn't have an optimistic branch block, LatestBranch is
417     // already pointing to the right place.
418     llvm::BasicBlock *BranchBB = Fixup.OptimisticBranchBlock;
419     if (!BranchBB)
420       continue;
421 
422     // Don't process the same optimistic branch block twice.
423     if (!ModifiedOptimisticBlocks.insert(BranchBB).second)
424       continue;
425 
426     llvm::SwitchInst *Switch = TransitionToCleanupSwitch(*this, BranchBB);
427 
428     // Add a case to the switch.
429     Switch->addCase(Builder.getInt32(Fixup.DestinationIndex), Block);
430   }
431 
432   if (ResolvedAny)
433     EHStack.popNullFixups();
434 }
435 
436 /// Pops cleanup blocks until the given savepoint is reached.
437 void CodeGenFunction::PopCleanupBlocks(
438     EHScopeStack::stable_iterator Old,
439     std::initializer_list<llvm::Value **> ValuesToReload) {
440   assert(Old.isValid());
441 
442   bool HadBranches = false;
443   while (EHStack.stable_begin() != Old) {
444     EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
445     HadBranches |= Scope.hasBranches();
446 
447     // As long as Old strictly encloses the scope's enclosing normal
448     // cleanup, we're going to emit another normal cleanup which
449     // fallthrough can propagate through.
450     bool FallThroughIsBranchThrough =
451       Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
452 
453     PopCleanupBlock(FallThroughIsBranchThrough);
454   }
455 
456   // If we didn't have any branches, the insertion point before cleanups must
457   // dominate the current insertion point and we don't need to reload any
458   // values.
459   if (!HadBranches)
460     return;
461 
462   // Spill and reload all values that the caller wants to be live at the current
463   // insertion point.
464   for (llvm::Value **ReloadedValue : ValuesToReload) {
465     auto *Inst = dyn_cast_or_null<llvm::Instruction>(*ReloadedValue);
466     if (!Inst)
467       continue;
468 
469     // Don't spill static allocas, they dominate all cleanups. These are created
470     // by binding a reference to a local variable or temporary.
471     auto *AI = dyn_cast<llvm::AllocaInst>(Inst);
472     if (AI && AI->isStaticAlloca())
473       continue;
474 
475     Address Tmp =
476         CreateDefaultAlignTempAlloca(Inst->getType(), "tmp.exprcleanup");
477 
478     // Find an insertion point after Inst and spill it to the temporary.
479     llvm::BasicBlock::iterator InsertBefore;
480     if (auto *Invoke = dyn_cast<llvm::InvokeInst>(Inst))
481       InsertBefore = Invoke->getNormalDest()->getFirstInsertionPt();
482     else
483       InsertBefore = std::next(Inst->getIterator());
484     CGBuilderTy(CGM, &*InsertBefore).CreateStore(Inst, Tmp);
485 
486     // Reload the value at the current insertion point.
487     *ReloadedValue = Builder.CreateLoad(Tmp);
488   }
489 }
490 
491 /// Pops cleanup blocks until the given savepoint is reached, then add the
492 /// cleanups from the given savepoint in the lifetime-extended cleanups stack.
493 void CodeGenFunction::PopCleanupBlocks(
494     EHScopeStack::stable_iterator Old, size_t OldLifetimeExtendedSize,
495     std::initializer_list<llvm::Value **> ValuesToReload) {
496   PopCleanupBlocks(Old, ValuesToReload);
497 
498   // Move our deferred cleanups onto the EH stack.
499   for (size_t I = OldLifetimeExtendedSize,
500               E = LifetimeExtendedCleanupStack.size(); I != E; /**/) {
501     // Alignment should be guaranteed by the vptrs in the individual cleanups.
502     assert((I % alignof(LifetimeExtendedCleanupHeader) == 0) &&
503            "misaligned cleanup stack entry");
504 
505     LifetimeExtendedCleanupHeader &Header =
506         reinterpret_cast<LifetimeExtendedCleanupHeader&>(
507             LifetimeExtendedCleanupStack[I]);
508     I += sizeof(Header);
509 
510     EHStack.pushCopyOfCleanup(Header.getKind(),
511                               &LifetimeExtendedCleanupStack[I],
512                               Header.getSize());
513     I += Header.getSize();
514 
515     if (Header.isConditional()) {
516       Address ActiveFlag =
517           reinterpret_cast<Address &>(LifetimeExtendedCleanupStack[I]);
518       initFullExprCleanupWithFlag(ActiveFlag);
519       I += sizeof(ActiveFlag);
520     }
521   }
522   LifetimeExtendedCleanupStack.resize(OldLifetimeExtendedSize);
523 }
524 
525 static llvm::BasicBlock *CreateNormalEntry(CodeGenFunction &CGF,
526                                            EHCleanupScope &Scope) {
527   assert(Scope.isNormalCleanup());
528   llvm::BasicBlock *Entry = Scope.getNormalBlock();
529   if (!Entry) {
530     Entry = CGF.createBasicBlock("cleanup");
531     Scope.setNormalBlock(Entry);
532   }
533   return Entry;
534 }
535 
536 /// Attempts to reduce a cleanup's entry block to a fallthrough.  This
537 /// is basically llvm::MergeBlockIntoPredecessor, except
538 /// simplified/optimized for the tighter constraints on cleanup blocks.
539 ///
540 /// Returns the new block, whatever it is.
541 static llvm::BasicBlock *SimplifyCleanupEntry(CodeGenFunction &CGF,
542                                               llvm::BasicBlock *Entry) {
543   llvm::BasicBlock *Pred = Entry->getSinglePredecessor();
544   if (!Pred) return Entry;
545 
546   llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Pred->getTerminator());
547   if (!Br || Br->isConditional()) return Entry;
548   assert(Br->getSuccessor(0) == Entry);
549 
550   // If we were previously inserting at the end of the cleanup entry
551   // block, we'll need to continue inserting at the end of the
552   // predecessor.
553   bool WasInsertBlock = CGF.Builder.GetInsertBlock() == Entry;
554   assert(!WasInsertBlock || CGF.Builder.GetInsertPoint() == Entry->end());
555 
556   // Kill the branch.
557   Br->eraseFromParent();
558 
559   // Replace all uses of the entry with the predecessor, in case there
560   // are phis in the cleanup.
561   Entry->replaceAllUsesWith(Pred);
562 
563   // Merge the blocks.
564   Pred->splice(Pred->end(), Entry);
565 
566   // Kill the entry block.
567   Entry->eraseFromParent();
568 
569   if (WasInsertBlock)
570     CGF.Builder.SetInsertPoint(Pred);
571 
572   return Pred;
573 }
574 
575 static void EmitCleanup(CodeGenFunction &CGF,
576                         EHScopeStack::Cleanup *Fn,
577                         EHScopeStack::Cleanup::Flags flags,
578                         Address ActiveFlag) {
579   // If there's an active flag, load it and skip the cleanup if it's
580   // false.
581   llvm::BasicBlock *ContBB = nullptr;
582   if (ActiveFlag.isValid()) {
583     ContBB = CGF.createBasicBlock("cleanup.done");
584     llvm::BasicBlock *CleanupBB = CGF.createBasicBlock("cleanup.action");
585     llvm::Value *IsActive
586       = CGF.Builder.CreateLoad(ActiveFlag, "cleanup.is_active");
587     CGF.Builder.CreateCondBr(IsActive, CleanupBB, ContBB);
588     CGF.EmitBlock(CleanupBB);
589   }
590 
591   // Ask the cleanup to emit itself.
592   Fn->Emit(CGF, flags);
593   assert(CGF.HaveInsertPoint() && "cleanup ended with no insertion point?");
594 
595   // Emit the continuation block if there was an active flag.
596   if (ActiveFlag.isValid())
597     CGF.EmitBlock(ContBB);
598 }
599 
600 static void ForwardPrebranchedFallthrough(llvm::BasicBlock *Exit,
601                                           llvm::BasicBlock *From,
602                                           llvm::BasicBlock *To) {
603   // Exit is the exit block of a cleanup, so it always terminates in
604   // an unconditional branch or a switch.
605   llvm::Instruction *Term = Exit->getTerminator();
606 
607   if (llvm::BranchInst *Br = dyn_cast<llvm::BranchInst>(Term)) {
608     assert(Br->isUnconditional() && Br->getSuccessor(0) == From);
609     Br->setSuccessor(0, To);
610   } else {
611     llvm::SwitchInst *Switch = cast<llvm::SwitchInst>(Term);
612     for (unsigned I = 0, E = Switch->getNumSuccessors(); I != E; ++I)
613       if (Switch->getSuccessor(I) == From)
614         Switch->setSuccessor(I, To);
615   }
616 }
617 
618 /// We don't need a normal entry block for the given cleanup.
619 /// Optimistic fixup branches can cause these blocks to come into
620 /// existence anyway;  if so, destroy it.
621 ///
622 /// The validity of this transformation is very much specific to the
623 /// exact ways in which we form branches to cleanup entries.
624 static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
625                                          EHCleanupScope &scope) {
626   llvm::BasicBlock *entry = scope.getNormalBlock();
627   if (!entry) return;
628 
629   // Replace all the uses with unreachable.
630   llvm::BasicBlock *unreachableBB = CGF.getUnreachableBlock();
631   for (llvm::BasicBlock::use_iterator
632          i = entry->use_begin(), e = entry->use_end(); i != e; ) {
633     llvm::Use &use = *i;
634     ++i;
635 
636     use.set(unreachableBB);
637 
638     // The only uses should be fixup switches.
639     llvm::SwitchInst *si = cast<llvm::SwitchInst>(use.getUser());
640     if (si->getNumCases() == 1 && si->getDefaultDest() == unreachableBB) {
641       // Replace the switch with a branch.
642       llvm::BranchInst::Create(si->case_begin()->getCaseSuccessor(), si);
643 
644       // The switch operand is a load from the cleanup-dest alloca.
645       llvm::LoadInst *condition = cast<llvm::LoadInst>(si->getCondition());
646 
647       // Destroy the switch.
648       si->eraseFromParent();
649 
650       // Destroy the load.
651       assert(condition->getOperand(0) == CGF.NormalCleanupDest.getPointer());
652       assert(condition->use_empty());
653       condition->eraseFromParent();
654     }
655   }
656 
657   assert(entry->use_empty());
658   delete entry;
659 }
660 
661 /// Pops a cleanup block.  If the block includes a normal cleanup, the
662 /// current insertion point is threaded through the cleanup, as are
663 /// any branch fixups on the cleanup.
664 void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
665   assert(!EHStack.empty() && "cleanup stack is empty!");
666   assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
667   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
668   assert(Scope.getFixupDepth() <= EHStack.getNumBranchFixups());
669 
670   // Remember activation information.
671   bool IsActive = Scope.isActive();
672   Address NormalActiveFlag =
673     Scope.shouldTestFlagInNormalCleanup() ? Scope.getActiveFlag()
674                                           : Address::invalid();
675   Address EHActiveFlag =
676     Scope.shouldTestFlagInEHCleanup() ? Scope.getActiveFlag()
677                                       : Address::invalid();
678 
679   // Check whether we need an EH cleanup.  This is only true if we've
680   // generated a lazy EH cleanup block.
681   llvm::BasicBlock *EHEntry = Scope.getCachedEHDispatchBlock();
682   assert(Scope.hasEHBranches() == (EHEntry != nullptr));
683   bool RequiresEHCleanup = (EHEntry != nullptr);
684   EHScopeStack::stable_iterator EHParent = Scope.getEnclosingEHScope();
685 
686   // Check the three conditions which might require a normal cleanup:
687 
688   // - whether there are branch fix-ups through this cleanup
689   unsigned FixupDepth = Scope.getFixupDepth();
690   bool HasFixups = EHStack.getNumBranchFixups() != FixupDepth;
691 
692   // - whether there are branch-throughs or branch-afters
693   bool HasExistingBranches = Scope.hasBranches();
694 
695   // - whether there's a fallthrough
696   llvm::BasicBlock *FallthroughSource = Builder.GetInsertBlock();
697   bool HasFallthrough = (FallthroughSource != nullptr && IsActive);
698 
699   // Branch-through fall-throughs leave the insertion point set to the
700   // end of the last cleanup, which points to the current scope.  The
701   // rest of IR gen doesn't need to worry about this; it only happens
702   // during the execution of PopCleanupBlocks().
703   bool HasPrebranchedFallthrough =
704     (FallthroughSource && FallthroughSource->getTerminator());
705 
706   // If this is a normal cleanup, then having a prebranched
707   // fallthrough implies that the fallthrough source unconditionally
708   // jumps here.
709   assert(!Scope.isNormalCleanup() || !HasPrebranchedFallthrough ||
710          (Scope.getNormalBlock() &&
711           FallthroughSource->getTerminator()->getSuccessor(0)
712             == Scope.getNormalBlock()));
713 
714   bool RequiresNormalCleanup = false;
715   if (Scope.isNormalCleanup() &&
716       (HasFixups || HasExistingBranches || HasFallthrough)) {
717     RequiresNormalCleanup = true;
718   }
719 
720   // If we have a prebranched fallthrough into an inactive normal
721   // cleanup, rewrite it so that it leads to the appropriate place.
722   if (Scope.isNormalCleanup() && HasPrebranchedFallthrough && !IsActive) {
723     llvm::BasicBlock *prebranchDest;
724 
725     // If the prebranch is semantically branching through the next
726     // cleanup, just forward it to the next block, leaving the
727     // insertion point in the prebranched block.
728     if (FallthroughIsBranchThrough) {
729       EHScope &enclosing = *EHStack.find(Scope.getEnclosingNormalCleanup());
730       prebranchDest = CreateNormalEntry(*this, cast<EHCleanupScope>(enclosing));
731 
732     // Otherwise, we need to make a new block.  If the normal cleanup
733     // isn't being used at all, we could actually reuse the normal
734     // entry block, but this is simpler, and it avoids conflicts with
735     // dead optimistic fixup branches.
736     } else {
737       prebranchDest = createBasicBlock("forwarded-prebranch");
738       EmitBlock(prebranchDest);
739     }
740 
741     llvm::BasicBlock *normalEntry = Scope.getNormalBlock();
742     assert(normalEntry && !normalEntry->use_empty());
743 
744     ForwardPrebranchedFallthrough(FallthroughSource,
745                                   normalEntry, prebranchDest);
746   }
747 
748   // If we don't need the cleanup at all, we're done.
749   if (!RequiresNormalCleanup && !RequiresEHCleanup) {
750     destroyOptimisticNormalEntry(*this, Scope);
751     EHStack.popCleanup(); // safe because there are no fixups
752     assert(EHStack.getNumBranchFixups() == 0 ||
753            EHStack.hasNormalCleanups());
754     return;
755   }
756 
757   // Copy the cleanup emission data out.  This uses either a stack
758   // array or malloc'd memory, depending on the size, which is
759   // behavior that SmallVector would provide, if we could use it
760   // here. Unfortunately, if you ask for a SmallVector<char>, the
761   // alignment isn't sufficient.
762   auto *CleanupSource = reinterpret_cast<char *>(Scope.getCleanupBuffer());
763   alignas(EHScopeStack::ScopeStackAlignment) char
764       CleanupBufferStack[8 * sizeof(void *)];
765   std::unique_ptr<char[]> CleanupBufferHeap;
766   size_t CleanupSize = Scope.getCleanupSize();
767   EHScopeStack::Cleanup *Fn;
768 
769   if (CleanupSize <= sizeof(CleanupBufferStack)) {
770     memcpy(CleanupBufferStack, CleanupSource, CleanupSize);
771     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferStack);
772   } else {
773     CleanupBufferHeap.reset(new char[CleanupSize]);
774     memcpy(CleanupBufferHeap.get(), CleanupSource, CleanupSize);
775     Fn = reinterpret_cast<EHScopeStack::Cleanup *>(CleanupBufferHeap.get());
776   }
777 
778   EHScopeStack::Cleanup::Flags cleanupFlags;
779   if (Scope.isNormalCleanup())
780     cleanupFlags.setIsNormalCleanupKind();
781   if (Scope.isEHCleanup())
782     cleanupFlags.setIsEHCleanupKind();
783 
784   // Under -EHa, invoke seh.scope.end() to mark scope end before dtor
785   bool IsEHa = getLangOpts().EHAsynch && !Scope.isLifetimeMarker();
786   const EHPersonality &Personality = EHPersonality::get(*this);
787   if (!RequiresNormalCleanup) {
788     // Mark CPP scope end for passed-by-value Arg temp
789     //   per Windows ABI which is "normally" Cleanup in callee
790     if (IsEHa && getInvokeDest() && Builder.GetInsertBlock()) {
791       if (Personality.isMSVCXXPersonality())
792         EmitSehCppScopeEnd();
793     }
794     destroyOptimisticNormalEntry(*this, Scope);
795     EHStack.popCleanup();
796   } else {
797     // If we have a fallthrough and no other need for the cleanup,
798     // emit it directly.
799     if (HasFallthrough && !HasPrebranchedFallthrough && !HasFixups &&
800         !HasExistingBranches) {
801 
802       // mark SEH scope end for fall-through flow
803       if (IsEHa && getInvokeDest()) {
804         if (Personality.isMSVCXXPersonality())
805           EmitSehCppScopeEnd();
806         else
807           EmitSehTryScopeEnd();
808       }
809 
810       destroyOptimisticNormalEntry(*this, Scope);
811       EHStack.popCleanup();
812 
813       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
814 
815     // Otherwise, the best approach is to thread everything through
816     // the cleanup block and then try to clean up after ourselves.
817     } else {
818       // Force the entry block to exist.
819       llvm::BasicBlock *NormalEntry = CreateNormalEntry(*this, Scope);
820 
821       // I.  Set up the fallthrough edge in.
822 
823       CGBuilderTy::InsertPoint savedInactiveFallthroughIP;
824 
825       // If there's a fallthrough, we need to store the cleanup
826       // destination index.  For fall-throughs this is always zero.
827       if (HasFallthrough) {
828         if (!HasPrebranchedFallthrough)
829           Builder.CreateStore(Builder.getInt32(0), getNormalCleanupDestSlot());
830 
831       // Otherwise, save and clear the IP if we don't have fallthrough
832       // because the cleanup is inactive.
833       } else if (FallthroughSource) {
834         assert(!IsActive && "source without fallthrough for active cleanup");
835         savedInactiveFallthroughIP = Builder.saveAndClearIP();
836       }
837 
838       // II.  Emit the entry block.  This implicitly branches to it if
839       // we have fallthrough.  All the fixups and existing branches
840       // should already be branched to it.
841       EmitBlock(NormalEntry);
842 
843       // intercept normal cleanup to mark SEH scope end
844       if (IsEHa && getInvokeDest()) {
845         if (Personality.isMSVCXXPersonality())
846           EmitSehCppScopeEnd();
847         else
848           EmitSehTryScopeEnd();
849       }
850 
851       // III.  Figure out where we're going and build the cleanup
852       // epilogue.
853 
854       bool HasEnclosingCleanups =
855         (Scope.getEnclosingNormalCleanup() != EHStack.stable_end());
856 
857       // Compute the branch-through dest if we need it:
858       //   - if there are branch-throughs threaded through the scope
859       //   - if fall-through is a branch-through
860       //   - if there are fixups that will be optimistically forwarded
861       //     to the enclosing cleanup
862       llvm::BasicBlock *BranchThroughDest = nullptr;
863       if (Scope.hasBranchThroughs() ||
864           (FallthroughSource && FallthroughIsBranchThrough) ||
865           (HasFixups && HasEnclosingCleanups)) {
866         assert(HasEnclosingCleanups);
867         EHScope &S = *EHStack.find(Scope.getEnclosingNormalCleanup());
868         BranchThroughDest = CreateNormalEntry(*this, cast<EHCleanupScope>(S));
869       }
870 
871       llvm::BasicBlock *FallthroughDest = nullptr;
872       SmallVector<llvm::Instruction*, 2> InstsToAppend;
873 
874       // If there's exactly one branch-after and no other threads,
875       // we can route it without a switch.
876       if (!Scope.hasBranchThroughs() && !HasFixups && !HasFallthrough &&
877           Scope.getNumBranchAfters() == 1) {
878         assert(!BranchThroughDest || !IsActive);
879 
880         // Clean up the possibly dead store to the cleanup dest slot.
881         llvm::Instruction *NormalCleanupDestSlot =
882             cast<llvm::Instruction>(getNormalCleanupDestSlot().getPointer());
883         if (NormalCleanupDestSlot->hasOneUse()) {
884           NormalCleanupDestSlot->user_back()->eraseFromParent();
885           NormalCleanupDestSlot->eraseFromParent();
886           NormalCleanupDest = Address::invalid();
887         }
888 
889         llvm::BasicBlock *BranchAfter = Scope.getBranchAfterBlock(0);
890         InstsToAppend.push_back(llvm::BranchInst::Create(BranchAfter));
891 
892       // Build a switch-out if we need it:
893       //   - if there are branch-afters threaded through the scope
894       //   - if fall-through is a branch-after
895       //   - if there are fixups that have nowhere left to go and
896       //     so must be immediately resolved
897       } else if (Scope.getNumBranchAfters() ||
898                  (HasFallthrough && !FallthroughIsBranchThrough) ||
899                  (HasFixups && !HasEnclosingCleanups)) {
900 
901         llvm::BasicBlock *Default =
902           (BranchThroughDest ? BranchThroughDest : getUnreachableBlock());
903 
904         // TODO: base this on the number of branch-afters and fixups
905         const unsigned SwitchCapacity = 10;
906 
907         // pass the abnormal exit flag to Fn (SEH cleanup)
908         cleanupFlags.setHasExitSwitch();
909 
910         llvm::LoadInst *Load =
911           createLoadInstBefore(getNormalCleanupDestSlot(), "cleanup.dest",
912                                nullptr);
913         llvm::SwitchInst *Switch =
914           llvm::SwitchInst::Create(Load, Default, SwitchCapacity);
915 
916         InstsToAppend.push_back(Load);
917         InstsToAppend.push_back(Switch);
918 
919         // Branch-after fallthrough.
920         if (FallthroughSource && !FallthroughIsBranchThrough) {
921           FallthroughDest = createBasicBlock("cleanup.cont");
922           if (HasFallthrough)
923             Switch->addCase(Builder.getInt32(0), FallthroughDest);
924         }
925 
926         for (unsigned I = 0, E = Scope.getNumBranchAfters(); I != E; ++I) {
927           Switch->addCase(Scope.getBranchAfterIndex(I),
928                           Scope.getBranchAfterBlock(I));
929         }
930 
931         // If there aren't any enclosing cleanups, we can resolve all
932         // the fixups now.
933         if (HasFixups && !HasEnclosingCleanups)
934           ResolveAllBranchFixups(*this, Switch, NormalEntry);
935       } else {
936         // We should always have a branch-through destination in this case.
937         assert(BranchThroughDest);
938         InstsToAppend.push_back(llvm::BranchInst::Create(BranchThroughDest));
939       }
940 
941       // IV.  Pop the cleanup and emit it.
942       EHStack.popCleanup();
943       assert(EHStack.hasNormalCleanups() == HasEnclosingCleanups);
944 
945       EmitCleanup(*this, Fn, cleanupFlags, NormalActiveFlag);
946 
947       // Append the prepared cleanup prologue from above.
948       llvm::BasicBlock *NormalExit = Builder.GetInsertBlock();
949       for (unsigned I = 0, E = InstsToAppend.size(); I != E; ++I)
950         InstsToAppend[I]->insertInto(NormalExit, NormalExit->end());
951 
952       // Optimistically hope that any fixups will continue falling through.
953       for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
954            I < E; ++I) {
955         BranchFixup &Fixup = EHStack.getBranchFixup(I);
956         if (!Fixup.Destination) continue;
957         if (!Fixup.OptimisticBranchBlock) {
958           createStoreInstBefore(Builder.getInt32(Fixup.DestinationIndex),
959                                 getNormalCleanupDestSlot(),
960                                 Fixup.InitialBranch);
961           Fixup.InitialBranch->setSuccessor(0, NormalEntry);
962         }
963         Fixup.OptimisticBranchBlock = NormalExit;
964       }
965 
966       // V.  Set up the fallthrough edge out.
967 
968       // Case 1: a fallthrough source exists but doesn't branch to the
969       // cleanup because the cleanup is inactive.
970       if (!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.
974         assert(!IsActive);
975         Builder.restoreIP(savedInactiveFallthroughIP);
976 
977       // Case 2: a fallthrough source exists and should branch to the
978       // cleanup, but we're not supposed to branch through to the next
979       // cleanup.
980       } else if (HasFallthrough && FallthroughDest) {
981         assert(!FallthroughIsBranchThrough);
982         EmitBlock(FallthroughDest);
983 
984       // Case 3: a fallthrough source exists and should branch to the
985       // cleanup and then through to the next.
986       } else if (HasFallthrough) {
987         // Everything is already set up for this.
988 
989       // Case 4: no fallthrough source exists.
990       } else {
991         Builder.ClearInsertionPoint();
992       }
993 
994       // VI.  Assorted cleaning.
995 
996       // Check whether we can merge NormalEntry into a single predecessor.
997       // This might invalidate (non-IR) pointers to NormalEntry.
998       llvm::BasicBlock *NewNormalEntry =
999         SimplifyCleanupEntry(*this, NormalEntry);
1000 
1001       // If it did invalidate those pointers, and NormalEntry was the same
1002       // as NormalExit, go back and patch up the fixups.
1003       if (NewNormalEntry != NormalEntry && NormalEntry == NormalExit)
1004         for (unsigned I = FixupDepth, E = EHStack.getNumBranchFixups();
1005                I < E; ++I)
1006           EHStack.getBranchFixup(I).OptimisticBranchBlock = NewNormalEntry;
1007     }
1008   }
1009 
1010   assert(EHStack.hasNormalCleanups() || EHStack.getNumBranchFixups() == 0);
1011 
1012   // Emit the EH cleanup if required.
1013   if (RequiresEHCleanup) {
1014     CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1015 
1016     EmitBlock(EHEntry);
1017 
1018     llvm::BasicBlock *NextAction = getEHDispatchBlock(EHParent);
1019 
1020     // Push a terminate scope or cleanupendpad scope around the potentially
1021     // throwing cleanups. For funclet EH personalities, the cleanupendpad models
1022     // program termination when cleanups throw.
1023     bool PushedTerminate = false;
1024     SaveAndRestore RestoreCurrentFuncletPad(CurrentFuncletPad);
1025     llvm::CleanupPadInst *CPI = nullptr;
1026 
1027     const EHPersonality &Personality = EHPersonality::get(*this);
1028     if (Personality.usesFuncletPads()) {
1029       llvm::Value *ParentPad = CurrentFuncletPad;
1030       if (!ParentPad)
1031         ParentPad = llvm::ConstantTokenNone::get(CGM.getLLVMContext());
1032       CurrentFuncletPad = CPI = Builder.CreateCleanupPad(ParentPad);
1033     }
1034 
1035     // Non-MSVC personalities need to terminate when an EH cleanup throws.
1036     if (!Personality.isMSVCPersonality()) {
1037       EHStack.pushTerminate();
1038       PushedTerminate = true;
1039     } else if (IsEHa && getInvokeDest()) {
1040       EmitSehCppScopeEnd();
1041     }
1042 
1043     // We only actually emit the cleanup code if the cleanup is either
1044     // active or was used before it was deactivated.
1045     if (EHActiveFlag.isValid() || IsActive) {
1046       cleanupFlags.setIsForEHCleanup();
1047       EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
1048     }
1049 
1050     if (CPI)
1051       Builder.CreateCleanupRet(CPI, NextAction);
1052     else
1053       Builder.CreateBr(NextAction);
1054 
1055     // Leave the terminate scope.
1056     if (PushedTerminate)
1057       EHStack.popTerminate();
1058 
1059     Builder.restoreIP(SavedIP);
1060 
1061     SimplifyCleanupEntry(*this, EHEntry);
1062   }
1063 }
1064 
1065 /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
1066 /// specified destination obviously has no cleanups to run.  'false' is always
1067 /// a conservatively correct answer for this method.
1068 bool CodeGenFunction::isObviouslyBranchWithoutCleanups(JumpDest Dest) const {
1069   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1070          && "stale jump destination");
1071 
1072   // Calculate the innermost active normal cleanup.
1073   EHScopeStack::stable_iterator TopCleanup =
1074     EHStack.getInnermostActiveNormalCleanup();
1075 
1076   // If we're not in an active normal cleanup scope, or if the
1077   // destination scope is within the innermost active normal cleanup
1078   // scope, we don't need to worry about fixups.
1079   if (TopCleanup == EHStack.stable_end() ||
1080       TopCleanup.encloses(Dest.getScopeDepth())) // works for invalid
1081     return true;
1082 
1083   // Otherwise, we might need some cleanups.
1084   return false;
1085 }
1086 
1087 
1088 /// Terminate the current block by emitting a branch which might leave
1089 /// the current cleanup-protected scope.  The target scope may not yet
1090 /// be known, in which case this will require a fixup.
1091 ///
1092 /// As a side-effect, this method clears the insertion point.
1093 void CodeGenFunction::EmitBranchThroughCleanup(JumpDest Dest) {
1094   assert(Dest.getScopeDepth().encloses(EHStack.stable_begin())
1095          && "stale jump destination");
1096 
1097   if (!HaveInsertPoint())
1098     return;
1099 
1100   // Create the branch.
1101   llvm::BranchInst *BI = Builder.CreateBr(Dest.getBlock());
1102 
1103   // Calculate the innermost active normal cleanup.
1104   EHScopeStack::stable_iterator
1105     TopCleanup = EHStack.getInnermostActiveNormalCleanup();
1106 
1107   // If we're not in an active normal cleanup scope, or if the
1108   // destination scope is within the innermost active normal cleanup
1109   // scope, we don't need to worry about fixups.
1110   if (TopCleanup == EHStack.stable_end() ||
1111       TopCleanup.encloses(Dest.getScopeDepth())) { // works for invalid
1112     Builder.ClearInsertionPoint();
1113     return;
1114   }
1115 
1116   // If we can't resolve the destination cleanup scope, just add this
1117   // to the current cleanup scope as a branch fixup.
1118   if (!Dest.getScopeDepth().isValid()) {
1119     BranchFixup &Fixup = EHStack.addBranchFixup();
1120     Fixup.Destination = Dest.getBlock();
1121     Fixup.DestinationIndex = Dest.getDestIndex();
1122     Fixup.InitialBranch = BI;
1123     Fixup.OptimisticBranchBlock = nullptr;
1124 
1125     Builder.ClearInsertionPoint();
1126     return;
1127   }
1128 
1129   // Otherwise, thread through all the normal cleanups in scope.
1130 
1131   // Store the index at the start.
1132   llvm::ConstantInt *Index = Builder.getInt32(Dest.getDestIndex());
1133   createStoreInstBefore(Index, getNormalCleanupDestSlot(), BI);
1134 
1135   // Adjust BI to point to the first cleanup block.
1136   {
1137     EHCleanupScope &Scope =
1138       cast<EHCleanupScope>(*EHStack.find(TopCleanup));
1139     BI->setSuccessor(0, CreateNormalEntry(*this, Scope));
1140   }
1141 
1142   // Add this destination to all the scopes involved.
1143   EHScopeStack::stable_iterator I = TopCleanup;
1144   EHScopeStack::stable_iterator E = Dest.getScopeDepth();
1145   if (E.strictlyEncloses(I)) {
1146     while (true) {
1147       EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(I));
1148       assert(Scope.isNormalCleanup());
1149       I = Scope.getEnclosingNormalCleanup();
1150 
1151       // If this is the last cleanup we're propagating through, tell it
1152       // that there's a resolved jump moving through it.
1153       if (!E.strictlyEncloses(I)) {
1154         Scope.addBranchAfter(Index, Dest.getBlock());
1155         break;
1156       }
1157 
1158       // Otherwise, tell the scope that there's a jump propagating
1159       // through it.  If this isn't new information, all the rest of
1160       // the work has been done before.
1161       if (!Scope.addBranchThrough(Dest.getBlock()))
1162         break;
1163     }
1164   }
1165 
1166   Builder.ClearInsertionPoint();
1167 }
1168 
1169 static bool IsUsedAsNormalCleanup(EHScopeStack &EHStack,
1170                                   EHScopeStack::stable_iterator C) {
1171   // If we needed a normal block for any reason, that counts.
1172   if (cast<EHCleanupScope>(*EHStack.find(C)).getNormalBlock())
1173     return true;
1174 
1175   // Check whether any enclosed cleanups were needed.
1176   for (EHScopeStack::stable_iterator
1177          I = EHStack.getInnermostNormalCleanup();
1178          I != C; ) {
1179     assert(C.strictlyEncloses(I));
1180     EHCleanupScope &S = cast<EHCleanupScope>(*EHStack.find(I));
1181     if (S.getNormalBlock()) return true;
1182     I = S.getEnclosingNormalCleanup();
1183   }
1184 
1185   return false;
1186 }
1187 
1188 static bool IsUsedAsEHCleanup(EHScopeStack &EHStack,
1189                               EHScopeStack::stable_iterator cleanup) {
1190   // If we needed an EH block for any reason, that counts.
1191   if (EHStack.find(cleanup)->hasEHBranches())
1192     return true;
1193 
1194   // Check whether any enclosed cleanups were needed.
1195   for (EHScopeStack::stable_iterator
1196          i = EHStack.getInnermostEHScope(); i != cleanup; ) {
1197     assert(cleanup.strictlyEncloses(i));
1198 
1199     EHScope &scope = *EHStack.find(i);
1200     if (scope.hasEHBranches())
1201       return true;
1202 
1203     i = scope.getEnclosingEHScope();
1204   }
1205 
1206   return false;
1207 }
1208 
1209 enum ForActivation_t {
1210   ForActivation,
1211   ForDeactivation
1212 };
1213 
1214 /// The given cleanup block is changing activation state.  Configure a
1215 /// cleanup variable if necessary.
1216 ///
1217 /// It would be good if we had some way of determining if there were
1218 /// extra uses *after* the change-over point.
1219 static void SetupCleanupBlockActivation(CodeGenFunction &CGF,
1220                                         EHScopeStack::stable_iterator C,
1221                                         ForActivation_t kind,
1222                                         llvm::Instruction *dominatingIP) {
1223   EHCleanupScope &Scope = cast<EHCleanupScope>(*CGF.EHStack.find(C));
1224 
1225   // We always need the flag if we're activating the cleanup in a
1226   // conditional context, because we have to assume that the current
1227   // location doesn't necessarily dominate the cleanup's code.
1228   bool isActivatedInConditional =
1229     (kind == ForActivation && CGF.isInConditionalBranch());
1230 
1231   bool needFlag = false;
1232 
1233   // Calculate whether the cleanup was used:
1234 
1235   //   - as a normal cleanup
1236   if (Scope.isNormalCleanup() &&
1237       (isActivatedInConditional || IsUsedAsNormalCleanup(CGF.EHStack, C))) {
1238     Scope.setTestFlagInNormalCleanup();
1239     needFlag = true;
1240   }
1241 
1242   //  - as an EH cleanup
1243   if (Scope.isEHCleanup() &&
1244       (isActivatedInConditional || IsUsedAsEHCleanup(CGF.EHStack, C))) {
1245     Scope.setTestFlagInEHCleanup();
1246     needFlag = true;
1247   }
1248 
1249   // If it hasn't yet been used as either, we're done.
1250   if (!needFlag) return;
1251 
1252   Address var = Scope.getActiveFlag();
1253   if (!var.isValid()) {
1254     var = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(), CharUnits::One(),
1255                                "cleanup.isactive");
1256     Scope.setActiveFlag(var);
1257 
1258     assert(dominatingIP && "no existing variable and no dominating IP!");
1259 
1260     // Initialize to true or false depending on whether it was
1261     // active up to this point.
1262     llvm::Constant *value = CGF.Builder.getInt1(kind == ForDeactivation);
1263 
1264     // If we're in a conditional block, ignore the dominating IP and
1265     // use the outermost conditional branch.
1266     if (CGF.isInConditionalBranch()) {
1267       CGF.setBeforeOutermostConditional(value, var);
1268     } else {
1269       createStoreInstBefore(value, var, dominatingIP);
1270     }
1271   }
1272 
1273   CGF.Builder.CreateStore(CGF.Builder.getInt1(kind == ForActivation), var);
1274 }
1275 
1276 /// Activate a cleanup that was created in an inactivated state.
1277 void CodeGenFunction::ActivateCleanupBlock(EHScopeStack::stable_iterator C,
1278                                            llvm::Instruction *dominatingIP) {
1279   assert(C != EHStack.stable_end() && "activating bottom of stack?");
1280   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1281   assert(!Scope.isActive() && "double activation");
1282 
1283   SetupCleanupBlockActivation(*this, C, ForActivation, dominatingIP);
1284 
1285   Scope.setActive(true);
1286 }
1287 
1288 /// Deactive a cleanup that was created in an active state.
1289 void CodeGenFunction::DeactivateCleanupBlock(EHScopeStack::stable_iterator C,
1290                                              llvm::Instruction *dominatingIP) {
1291   assert(C != EHStack.stable_end() && "deactivating bottom of stack?");
1292   EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.find(C));
1293   assert(Scope.isActive() && "double deactivation");
1294 
1295   // If it's the top of the stack, just pop it, but do so only if it belongs
1296   // to the current RunCleanupsScope.
1297   if (C == EHStack.stable_begin() &&
1298       CurrentCleanupScopeDepth.strictlyEncloses(C)) {
1299     // Per comment below, checking EHAsynch is not really necessary
1300     // it's there to assure zero-impact w/o EHAsynch option
1301     if (!Scope.isNormalCleanup() && getLangOpts().EHAsynch) {
1302       PopCleanupBlock();
1303     } else {
1304       // If it's a normal cleanup, we need to pretend that the
1305       // fallthrough is unreachable.
1306       CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
1307       PopCleanupBlock();
1308       Builder.restoreIP(SavedIP);
1309     }
1310     return;
1311   }
1312 
1313   // Otherwise, follow the general case.
1314   SetupCleanupBlockActivation(*this, C, ForDeactivation, dominatingIP);
1315 
1316   Scope.setActive(false);
1317 }
1318 
1319 Address CodeGenFunction::getNormalCleanupDestSlot() {
1320   if (!NormalCleanupDest.isValid())
1321     NormalCleanupDest =
1322       CreateDefaultAlignTempAlloca(Builder.getInt32Ty(), "cleanup.dest.slot");
1323   return NormalCleanupDest;
1324 }
1325 
1326 /// Emits all the code to cause the given temporary to be cleaned up.
1327 void CodeGenFunction::EmitCXXTemporary(const CXXTemporary *Temporary,
1328                                        QualType TempType,
1329                                        Address Ptr) {
1330   pushDestroy(NormalAndEHCleanup, Ptr, TempType, destroyCXXObject,
1331               /*useEHCleanup*/ true);
1332 }
1333 
1334 // Need to set "funclet" in OperandBundle properly for noThrow
1335 //       intrinsic (see CGCall.cpp)
1336 static void EmitSehScope(CodeGenFunction &CGF,
1337                          llvm::FunctionCallee &SehCppScope) {
1338   llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
1339   assert(CGF.Builder.GetInsertBlock() && InvokeDest);
1340   llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
1341   SmallVector<llvm::OperandBundleDef, 1> BundleList =
1342       CGF.getBundlesForFunclet(SehCppScope.getCallee());
1343   if (CGF.CurrentFuncletPad)
1344     BundleList.emplace_back("funclet", CGF.CurrentFuncletPad);
1345   CGF.Builder.CreateInvoke(SehCppScope, Cont, InvokeDest, std::nullopt,
1346                            BundleList);
1347   CGF.EmitBlock(Cont);
1348 }
1349 
1350 // Invoke a llvm.seh.scope.begin at the beginning of a CPP scope for -EHa
1351 void CodeGenFunction::EmitSehCppScopeBegin() {
1352   assert(getLangOpts().EHAsynch);
1353   llvm::FunctionType *FTy =
1354       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1355   llvm::FunctionCallee SehCppScope =
1356       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.begin");
1357   EmitSehScope(*this, SehCppScope);
1358 }
1359 
1360 // Invoke a llvm.seh.scope.end at the end of a CPP scope for -EHa
1361 //   llvm.seh.scope.end is emitted before popCleanup, so it's "invoked"
1362 void CodeGenFunction::EmitSehCppScopeEnd() {
1363   assert(getLangOpts().EHAsynch);
1364   llvm::FunctionType *FTy =
1365       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1366   llvm::FunctionCallee SehCppScope =
1367       CGM.CreateRuntimeFunction(FTy, "llvm.seh.scope.end");
1368   EmitSehScope(*this, SehCppScope);
1369 }
1370 
1371 // Invoke a llvm.seh.try.begin at the beginning of a SEH scope for -EHa
1372 void CodeGenFunction::EmitSehTryScopeBegin() {
1373   assert(getLangOpts().EHAsynch);
1374   llvm::FunctionType *FTy =
1375       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1376   llvm::FunctionCallee SehCppScope =
1377       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.begin");
1378   EmitSehScope(*this, SehCppScope);
1379 }
1380 
1381 // Invoke a llvm.seh.try.end at the end of a SEH scope for -EHa
1382 void CodeGenFunction::EmitSehTryScopeEnd() {
1383   assert(getLangOpts().EHAsynch);
1384   llvm::FunctionType *FTy =
1385       llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
1386   llvm::FunctionCallee SehCppScope =
1387       CGM.CreateRuntimeFunction(FTy, "llvm.seh.try.end");
1388   EmitSehScope(*this, SehCppScope);
1389 }
1390