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