31class ConditionalEvaluationFinder
33 bool foundConditional =
false;
36 bool found()
const {
return foundConditional; }
38 bool VisitAbstractConditionalOperator(AbstractConditionalOperator *) {
39 foundConditional =
true;
43 bool VisitBinaryOperator(BinaryOperator *e) {
45 foundConditional =
true;
51 bool VisitCXXNewExpr(CXXNewExpr *e) {
56 foundConditional =
true;
63 bool TraverseLambdaExpr(
LambdaExpr *) {
return true; }
64 bool TraverseBlockExpr(BlockExpr *) {
return true; }
65 bool TraverseStmtExpr(StmtExpr *) {
return true; }
81 mlir::Location loc = builder.getUnknownLoc();
94 mlir::OpBuilder::InsertionGuard guard(builder);
97 builder.createFlagStore(loc,
false, active.
getPointer());
102 builder.createFlagStore(loc,
true, active.
getPointer());
113 assert(!cleanup.hasActiveFlag() &&
"cleanup already has active flag?");
114 cleanup.setActiveFlag(activeFlag);
116 cleanup.setTestFlagInNormalCleanup(cleanup.isNormalCleanup());
117 cleanup.setTestFlagInEHCleanup(cleanup.isEHCleanup());
122 : cgf(cgf), cleanups(cgf), scope(
nullptr),
127 assert(subExpr &&
"ExprWithCleanups always has a sub-expression");
128 ConditionalEvaluationFinder finder;
129 finder.TraverseStmt(
const_cast<Expr *
>(subExpr));
130 if (finder.found()) {
131 mlir::Location loc = cgf.builder.getUnknownLoc();
132 cir::CleanupKind cleanupKind = cgf.getLangOpts().Exceptions
133 ? cir::CleanupKind::All
134 : cir::CleanupKind::Normal;
135 scope = cir::CleanupScopeOp::create(
136 cgf.builder, loc, cleanupKind,
138 [&](mlir::OpBuilder &b, mlir::Location loc) {},
140 [&](mlir::OpBuilder &b, mlir::Location loc) {});
141 cgf.builder.setInsertionPointToEnd(&scope.getBodyRegion().front());
146 cgf.currentFullExprCleanupScope = scope;
153 cir::CleanupScopeOp scope) {
160 auto cur = alloca->getParentOfType<cir::CleanupScopeOp>();
161 while (cur && cur != scope)
162 cur = cur->getParentOfType<cir::CleanupScopeOp>();
169 mlir::Block *parentBlock = scope->getBlock();
170 mlir::OpBuilder::InsertPoint ip =
172 alloca->moveBefore(parentBlock, ip.getPoint());
181 for (mlir::Operation *cur = ptr.getDefiningOp(); cur && cur != alloca;) {
182 auto cast = mlir::dyn_cast<cir::CastOp>(cur);
185 casts.push_back(
cast);
186 cur =
cast.getSrc().getDefiningOp();
189 mlir::Operation *prev = alloca;
190 for (cir::CastOp
cast : llvm::reverse(casts)) {
191 cast->moveAfter(prev);
204 cir::CleanupScopeOp scope = condScope.
scope;
207 bool hasDeferredCleanups = stack.size() > base;
211 mlir::OpBuilder::InsertionGuard guard(builder);
212 mlir::Block &lastBodyBlock = scope.getBodyRegion().back();
213 builder.setInsertionPointToEnd(&lastBodyBlock);
214 if (lastBodyBlock.empty() ||
215 !lastBodyBlock.back().hasTrait<mlir::OpTrait::IsTerminator>())
223 if (hasDeferredCleanups) {
225 llvm::make_range(stack.begin() + base, stack.end()))
230 mlir::OpBuilder::InsertionGuard guard(builder);
231 mlir::Block &cleanupBlock = scope.getCleanupRegion().front();
232 builder.setInsertionPointToEnd(&cleanupBlock);
235 llvm::reverse(llvm::make_range(stack.begin() + base, stack.end()))) {
236 if (entry.activeFlag.isValid()) {
244 assert(entry.addr.getUnderlyingAllocaOp() &&
245 (entry.addr.getUnderlyingAllocaOp()->getBlock() ==
246 entry.addr.getPointer().getDefiningOp()->getBlock()) &&
247 "alloca and cast are in different blocks");
248 mlir::Value flag = builder.
createLoad(scope.getLoc(), entry.activeFlag);
249 cir::IfOp::create(builder, scope.getLoc(), flag,
251 [&](mlir::OpBuilder &b, mlir::Location loc) {
252 cgf.emitDestroy(entry.addr, entry.type,
254 builder.createYield(loc);
257 cgf.
emitDestroy(entry.addr, entry.type, entry.destroyer);
263 stack.truncate(base);
269 mlir::Block *insertBlock = builder.getInsertionBlock();
271 scope.getBodyRegion().findAncestorBlockInRegion(*insertBlock))
272 builder.setInsertionPointAfter(scope);
277 assert(!exited &&
"FullExprCleanupScope::exit called twice");
280 cgf.currentFullExprCleanupScope = oldFullExprCleanupScope;
282 size_t oldSize = deferredCleanupStackSize;
285 assert(cgf.conditionalCleanupScopes.size() == conditionalScopeDepth &&
286 "conditional cleanup scope opened without one to close it");
287 cgf.deferredConditionalCleanupStack.truncate(oldSize);
288 cleanups.forceCleanup(valuesToReload);
294 for (mlir::Value *valPtr : valuesToReload) {
295 mlir::Value val = *valPtr;
300 Address temp = cgf.createDefaultAlignTempAlloca(val.getType(), val.getLoc(),
302 tempAllocas.push_back(temp);
303 cgf.builder.createStore(val.getLoc(), val, temp);
309 while (cgf.conditionalCleanupScopes.size() > conditionalScopeDepth)
311 cgf.conditionalCleanupScopes.pop_back_val());
316 cleanups.forceCleanupExceptLifetimeExtended();
320 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
321 mlir::Block &lastBodyBlock = scope.getBodyRegion().back();
322 cgf.builder.setInsertionPointToEnd(&lastBodyBlock);
323 if (lastBodyBlock.empty() ||
324 !lastBodyBlock.back().hasTrait<mlir::OpTrait::IsTerminator>())
325 cgf.builder.createYield(scope.getLoc());
332 mlir::OpBuilder::InsertionGuard guard(cgf.builder);
333 mlir::Block &cleanupBlock = scope.getCleanupRegion().front();
334 cgf.builder.setInsertionPointToEnd(&cleanupBlock);
335 cgf.builder.createYield(scope.getLoc());
338 assert(cgf.deferredConditionalCleanupStack.size() == oldSize &&
339 "deferred cleanups were not consumed by a conditional scope");
340 cgf.builder.setInsertionPointAfter(scope);
346 cleanups.forceLifetimeExtendedCleanups();
349 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
352 *valPtr = cgf.builder.createLoad(valPtr->getLoc(), addr);
360void EHScopeStack::Cleanup::anchor() {}
364 stable_iterator si = getInnermostNormalCleanup();
365 stable_iterator se = stable_end();
368 if (cleanup.isActive())
370 si = cleanup.getEnclosingNormalCleanup();
376char *EHScopeStack::allocate(
size_t size) {
377 size = llvm::alignTo(size, ScopeStackAlignment);
378 if (!startOfBuffer) {
379 unsigned capacity = llvm::PowerOf2Ceil(std::max<size_t>(size, 1024ul));
380 startOfBuffer = std::make_unique<char[]>(capacity);
381 startOfData = endOfBuffer = startOfBuffer.get() + capacity;
382 }
else if (
static_cast<size_t>(startOfData - startOfBuffer.get()) < size) {
383 unsigned currentCapacity = endOfBuffer - startOfBuffer.get();
384 unsigned usedCapacity =
385 currentCapacity - (startOfData - startOfBuffer.get());
386 unsigned requiredCapacity = usedCapacity + size;
389 unsigned newCapacity = llvm::PowerOf2Ceil(requiredCapacity);
391 std::unique_ptr<char[]> newStartOfBuffer =
392 std::make_unique<char[]>(newCapacity);
393 char *newEndOfBuffer = newStartOfBuffer.get() + newCapacity;
394 char *newStartOfData = newEndOfBuffer - usedCapacity;
395 memcpy(newStartOfData, startOfData, usedCapacity);
396 startOfBuffer.swap(newStartOfBuffer);
397 endOfBuffer = newEndOfBuffer;
398 startOfData = newStartOfData;
401 assert(startOfBuffer.get() + size <= startOfData);
406void EHScopeStack::deallocate(
size_t size) {
407 startOfData += llvm::alignTo(size, ScopeStackAlignment);
415 bool skipCleanupScope =
false;
417 cir::CleanupKind cleanupKind = cir::CleanupKind::All;
418 if (isEHCleanup && cgf->getLangOpts().Exceptions) {
420 isNormalCleanup ? cir::CleanupKind::All : cir::CleanupKind::EH;
426 cleanupKind = cir::CleanupKind::Normal;
428 skipCleanupScope =
true;
434 if (capturingLoopConditionCleanups)
435 skipCleanupScope =
true;
437 cir::CleanupScopeOp cleanupScope =
nullptr;
438 if (!skipCleanupScope) {
439 CIRGenBuilderTy &builder = cgf->getBuilder();
440 mlir::Location loc = builder.getUnknownLoc();
441 cleanupScope = cir::CleanupScopeOp::create(
442 builder, loc, cleanupKind,
444 [&](mlir::OpBuilder &b, mlir::Location loc) {
448 [&](mlir::OpBuilder &b, mlir::Location loc) {
452 builder.setInsertionPointToEnd(&cleanupScope.getBodyRegion().back());
459 if (innermostEHScope != stable_end() &&
463 EHCleanupScope *scope =
new (buffer)
464 EHCleanupScope(isNormalCleanup, isEHCleanup, size, cleanupScope,
465 innermostNormalCleanup, innermostEHScope);
468 innermostNormalCleanup = stable_begin();
471 innermostEHScope = stable_begin();
473 if (isLifetimeMarker)
477 if (cgf->getLangOpts().EHAsynch && isEHCleanup && !isLifetimeMarker &&
478 cgf->getTarget().getCXXABI().isMicrosoft())
479 cgf->cgm.errorNYI(
"push seh cleanup");
485 assert(!empty() &&
"popping exception stack when not empty");
489 innermostNormalCleanup =
cleanup.getEnclosingNormalCleanup();
490 innermostEHScope =
cleanup.getEnclosingEHScope();
491 deallocate(
cleanup.getAllocatedSize());
493 cir::CleanupScopeOp cleanupScope =
cleanup.getCleanupScopeOp();
495 auto *block = &cleanupScope.getBodyRegion().back();
496 if (!block->mightHaveTerminator()) {
497 mlir::OpBuilder::InsertionGuard guard(cgf->getBuilder());
498 cgf->getBuilder().setInsertionPointToEnd(block);
499 cir::YieldOp::create(cgf->getBuilder(),
500 cgf->getBuilder().getUnknownLoc());
504 mlir::Block *insertBlock = cgf->getBuilder().getInsertionBlock();
506 cleanupScope.getBodyRegion().findAncestorBlockInRegion(*insertBlock))
507 cgf->getBuilder().setInsertionPointAfter(cleanupScope);
515 for (stable_iterator si = getInnermostEHScope(); si != stable_end();) {
516 if (
auto *cleanup = dyn_cast<EHCleanupScope>(&*find(si))) {
517 if (
cleanup->isLifetimeMarker()) {
519 si =
cleanup->getEnclosingEHScope();
532 mlir::Operation *dominatingIP) {
536 "cleanup block is neither normal nor EH?");
547 if (!var.isValid()) {
548 mlir::Location loc = builder.getUnknownLoc();
551 loc,
"cleanup.isactive");
554 assert(dominatingIP &&
"no existing variable and no dominating IP!");
557 mlir::Value val = builder.
getBool(
true, loc);
560 mlir::OpBuilder::InsertionGuard guard(builder);
561 builder.setInsertionPoint(dominatingIP);
569 mlir::Location loc = builder.getUnknownLoc();
575 mlir::Operation *dominatingIP) {
576 assert(c !=
ehStack.stable_end() &&
"deactivating bottom of stack?");
578 assert(scope.
isActive() &&
"double deactivation");
582 if (c ==
ehStack.stable_begin() &&
596 Address activeFlag, mlir::Location loc) {
604 cir::IfOp::create(builder, loc, isActive,
607 [&](mlir::OpBuilder &, mlir::Location) {
608 cleanup->emit(cgf, flags);
610 "cleanup ended with no insertion point?");
614 cleanup->emit(cgf, flags);
615 assert(cgf.
haveInsertPoint() &&
"cleanup ended with no insertion point?");
620 EHScopeStack::Cleanup *cleanup,
624 mlir::Block &block = cleanupScope.getCleanupRegion().back();
626 mlir::OpBuilder::InsertionGuard guard(builder);
627 builder.setInsertionPointToStart(&block);
629 emitCleanupBody(cgf, cleanup, flags, activeFlag, cleanupScope.getLoc());
631 mlir::Block &cleanupRegionLastBlock = cleanupScope.getCleanupRegion().back();
632 if (cleanupRegionLastBlock.empty() ||
633 !cleanupRegionLastBlock.back().hasTrait<mlir::OpTrait::IsTerminator>()) {
634 mlir::OpBuilder::InsertionGuard guardCase(builder);
635 builder.setInsertionPointToEnd(&cleanupRegionLastBlock);
646 .walk([&](mlir::Operation *op) {
648 return mlir::WalkResult::interrupt();
649 return mlir::WalkResult::advance();
659 assert(!
ehStack.empty() &&
"cleanup stack is empty!");
669 "missing cir.cleanup.scope for active cleanup");
691 if (forDeactivation && requiresNormalCleanup) {
698 mlir::Location loc = builder.getUnknownLoc();
705 mlir::OpBuilder::InsertionGuard guard(builder);
706 builder.setInsertionPoint(cleanupScope);
707 builder.createFlagStore(loc,
true, activeFlag.
getPointer());
711 assert(builder.getInsertionBlock() ==
712 &cleanupScope.getBodyRegion().back() &&
713 "expected insertion point in cleanup body");
714 builder.createFlagStore(loc,
false, activeFlag.
getPointer());
721 if (requiresEHCleanup)
722 cleanupScope.setCleanupKind(cir::CleanupKind::EH);
723 requiresNormalCleanup =
false;
735 if (!requiresNormalCleanup && !requiresEHCleanup) {
740 mlir::Block &cleanupBlock = cleanupScope.getCleanupRegion().back();
741 if (!cleanupBlock.mightHaveTerminator()) {
742 mlir::OpBuilder::InsertionGuard guard(builder);
743 builder.setInsertionPointToEnd(&cleanupBlock);
744 cir::YieldOp::create(builder, builder.getUnknownLoc());
757 cleanupBufferStack[8 *
sizeof(
void *)];
758 std::unique_ptr<char[]> cleanupBufferHeap;
764 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
765 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
768 cleanupBufferHeap.reset(
new char[cleanupSize]);
769 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
781 Address cleanupActiveFlag = normalActiveFlag.
isValid() ? normalActiveFlag
782 : ehActiveFlag.
isValid() ? ehActiveFlag
790 emitCleanup(*
this, cleanupScope, cleanup, cleanupFlags, cleanupActiveFlag);
799 while (
ehStack.stable_begin() != depth) {
803 "captured loop-condition cleanup should not own a cleanup scope");
823 cleanupBufferStack[8 *
sizeof(
void *)];
824 std::unique_ptr<char[]> cleanupBufferHeap;
827 if (cleanupSize <=
sizeof(cleanupBufferStack)) {
828 memcpy(cleanupBufferStack, cleanupSource, cleanupSize);
831 cleanupBufferHeap.reset(
new char[cleanupSize]);
832 memcpy(cleanupBufferHeap.get(), cleanupSource, cleanupSize);
849 bool requiresCleanup =
false;
850 for (
auto it =
ehStack.begin(), ie =
ehStack.find(oldCleanupStackDepth);
853 requiresCleanup =
true;
862 if (requiresCleanup) {
863 for (mlir::Value *valPtr : valuesToReload) {
864 mlir::Value val = *valPtr;
872 tempAllocas.push_back(temp);
873 builder.createStore(val.getLoc(), val, temp);
879 while (
ehStack.stable_begin() != oldCleanupStackDepth)
883 if (requiresCleanup) {
884 for (
auto [addr, valPtr] : llvm::zip(tempAllocas, valuesToReload)) {
885 mlir::Location loc = valPtr->getLoc();
886 *valPtr = builder.createLoad(loc, addr);
static void setupCleanupBlockDeactivation(CIRGenFunction &cgf, EHScopeStack::stable_iterator c, mlir::Operation *dominatingIP)
The given cleanup block is being deactivated.
static bool bodyHasBranchThroughExits(mlir::Region &bodyRegion)
Check whether a cleanup scope body contains any non-yield exits that branch through the cleanup.
static void closeConditionalCleanupScope(CIRGenFunction &cgf, const CIRGenFunction::ConditionalCleanupScope &condScope)
Close a cleanup scope opened by a ConditionalEvaluation.
static void hoistAllocaOutOfCleanupScope(CIRGenFunction &cgf, Address addr, cir::CleanupScopeOp scope)
If the alloca that backs addr is currently nested inside the body region of scope,...
static void emitCleanupBody(CIRGenFunction &cgf, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag, mlir::Location loc)
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static Decl::Kind getKind(const Decl *D)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
cir::ConstantOp getBool(bool state, mlir::Location loc)
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
static OpBuilder::InsertPoint getBestAllocaInsertPoint(mlir::Block *block)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
cir::BoolType getBoolTy()
static bool isLogicalOp(Opcode Opc)
mlir::Value getPointer() const
cir::AllocaOp getUnderlyingAllocaOp() const
Return the underlying alloca for this address, if any.
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false, bool isNontemporal=false)
FullExprCleanupScope(CIRGenFunction &cgf, const Expr *subExpr)
void exit(ArrayRef< mlir::Value * > valuesToReload={})
llvm::SmallVector< PendingCleanupEntry > lifetimeExtendedCleanupStack
void initFullExprCleanup()
Set up the last cleanup that was pushed as a conditional full-expression cleanup.
mlir::Block * getCurFunctionEntryBlock()
void emitLoopConditionCleanups(EHScopeStack::stable_iterator depth, mlir::Location loc)
Emit the cleanups captured for a loop's condition variable (those pushed above depth while EHScopeSta...
bool isInConditionalBranch() const
void setBeforeOutermostConditional(mlir::Value value, Address addr)
ConditionalEvaluation * outermostConditional
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
llvm::SmallVector< PendingCleanupEntry > deferredConditionalCleanupStack
Cleanups for temporaries constructed inside a conditional.
llvm::SmallVector< ConditionalCleanupScope > conditionalCleanupScopes
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
static Destroyer destroyCXXObject
void initFullExprCleanupWithFlag(Address activeFlag)
Address createCleanupActiveFlag()
Create an active flag variable for use with conditional cleanups.
void deactivateCleanupBlock(EHScopeStack::stable_iterator cleanup, mlir::Operation *dominatingIP)
Deactivates the given cleanup block.
bool haveInsertPoint() const
True if an insertion point is defined.
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
void popCleanupBlocks(EHScopeStack::stable_iterator oldCleanupStackDepth, ArrayRef< mlir::Value * > valuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
CIRGenBuilderTy & getBuilder()
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
void pushPendingCleanupToEHStack(const PendingCleanupEntry &entry)
Promote a single pending cleanup entry onto the EH scope stack.
void popCleanupBlock(bool forDeactivation=false)
Pop a cleanup block from the stack.
cir::CleanupScopeOp currentFullExprCleanupScope
The cir.cleanup.scope of the innermost FullExprCleanupScope that materialized one,...
EHScopeStack::stable_iterator currentCleanupStackDepth
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, mlir::OpBuilder::InsertPoint ip={})
This creates a alloca and inserts it into the entry block of the current region.
Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name)
CreateDefaultAlignTempAlloca - This creates an alloca with the default alignment of the corresponding...
A cleanup scope which generates the cleanup blocks lazily.
void setTestFlagInEHCleanup(bool value)
void setTestFlagInNormalCleanup(bool value)
Address getActiveFlag() const
size_t getCleanupSize() const
cir::CleanupScopeOp getCleanupScopeOp()
bool shouldTestFlagInEHCleanup() const
static size_t getSizeForCleanupSize(size_t size)
Gets the size required for a lazy cleanup scope with the given cleanup-data requirements.
bool isNormalCleanup() const
void setActiveFlag(Address var)
void * getCleanupBuffer()
bool shouldTestFlagInNormalCleanup() const
void setActive(bool isActive)
void setIsEHCleanupKind()
void setIsNormalCleanupKind()
Information for lazily generating a cleanup.
A saved depth on the scope stack.
void popCleanup()
Pops a cleanup scope off the stack. This is private to CIRGenCleanup.cpp.
iterator find(stable_iterator savePoint) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
bool requiresCatchOrCleanup() const
stable_iterator getInnermostActiveNormalCleanup() const
bool hasInitializer() const
Whether this new-expression has any initializer at all.
bool shouldNullCheckAllocation() const
True if the allocation result needs to be null-checked.
Represents a C++ temporary.
static CharUnits One()
One - Construct a CharUnits quantity of one.
This represents one expression.
A (possibly-)qualified type.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
One record per cir.cleanup.scope opened by a ConditionalEvaluation, as described above.
size_t deferredCleanupStackSize
The size of deferredConditionalCleanupStack when this scope was opened.
cir::CleanupScopeOp scope
A cleanup whose destructor call is not emitted where the cleanup is registered.