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