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