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