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