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