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