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